方法一:indexOf()
indexOf()方法返回在数组中可以找到给定元素的第一个索引,如果不存在,则返回-1。
示例:
let arr = [1, "1", 3, 3, "hello", "hello", true, true, false, false, "true", {}, {}];
let res = [];
for (let i = 0; i < arr.length; i++) {
if (res.indexOf(arr[i]) === -1) { // 若res数组中没找到当前值,则放入res数组中
res.push(arr[i]);
}
}
console.log(res); //[1, '1', 3, 'hello', true, false, 'true', {}, {}]
方法二:includes()
Array.includes()方法用来判断一个数组中是否包含一个特定的值,如果包含则返回true,否则返回false。
示例:
let arr = [1, "1", 3, 3, "hello", "hello", true, true, false, false, "true", {}, {}];
let res = [];
for (let i = 0; i < arr.length; i++) {
if (!res.includes(arr[i])) { // res数组中没找到当前值,则放入res数组中
res.push(arr[i]);
}
}
console.log(res); //[1, '1', 3, 'hello', true, false, 'true', {}, {}]
方法三:filter() + indexOf()
indexOf()方法返回在数组中可以找到给定元素的第一个索引,如果不存在,则返回-1。
Array.filter()方法创建给定数组一部分的浅拷贝,其包含通过所提供函数实现的测试的所有元素
示例:
let arr = [1, "1", 3, 3, "hello", "hello", true, true, false, false, "true", {}, {}];
let res = arr.filter((item, index) => {
return arr.indexOf(item) === index;
});
console.log(res); //[1, '1', 3, 'hello', true, false, 'true', {}, {}]
方法四:Set对象 + Array.from()
Set对象允许存储任何类型的唯一值。Set中的元素只会出现一次,即Set中的元素是唯一的。
Array.from()方法对一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例。
示例:
let arr = [1, "1", 3, 3, "hello", "hello", true, true, false, false, "true", {}, {}];
let set = new Set(arr);
let res = Array.from(set);
console.log(res); //[1, '1', 3, 'hello', true, false, 'true', {}, {}]
方法五:Map对象
Map对象是键值对的集合,其中的每一个键只能出现一次。Map对象的has()和set()方法可以判断键是否重复。
示例:
let arr = [1, "1", 3, 3, "hello", "hello", true, true, false, false, "true", {}, {}];
let res = [];
let map = new Map();
for (let i = 0; i < arr.length; i++) {
if (!map.has(arr[i])) { // 使用has()判断map是否存在当前键
map.set(arr[i], true); // 使用set()将当前值作为键名,true作为值存入map中
res.push(arr[i]);
}
}
console.log(res); //[1, '1', 3, 'hello', true, false, 'true', {}, {}]