📅  最后修改于: 2023-12-03 15:38:40.228000             🧑  作者: Mango
在程序开发中,经常会遇到需要从一个数组中获取唯一的名称的情况,本文将介绍如何使用JavaScript解决这个问题。
使用ES6中的Set可以快速获取一个数组中的唯一名称,示例代码如下:
const names = ['Tom', 'Jerry', 'Tom', 'Lucy', 'Jerry'];
const uniqueNames = [...new Set(names)];
console.log(uniqueNames); // ['Tom', 'Jerry', 'Lucy']
解析:
names
。new Set(names)
创建一个Set对象,Set是ES6中新增的一种数据结构,它可以保存一组不重复的值。...
将Set对象转化为数组,即可得到一个不包含重复名称的数组uniqueNames
。如果你的运行环境不支持ES6的Set,也可以使用for循环遍历数组来获取唯一名称,示例代码如下:
const names = ['Tom', 'Jerry', 'Tom', 'Lucy', 'Jerry'];
const uniqueNames = [];
for(let i = 0; i < names.length; i++) {
if(uniqueNames.indexOf(names[i]) === -1) {
uniqueNames.push(names[i]);
}
}
console.log(uniqueNames); // ['Tom', 'Jerry', 'Lucy']
解析:
names
和一个空数组uniqueNames
用于保存唯一名称。names
,对于每一个元素,使用indexOf
方法查找其在uniqueNames
中的位置。uniqueNames
中不存在,将其添加到uniqueNames
中去。uniqueNames
即为不包含重复名称的数组。可以看出,使用ES6中的Set可以更加简洁和高效地获取一个数组中的唯一名称,但是如果你需要兼容较老的运行环境,for循环的方法也是一个稳妥的选择。