for循环?NONONO
ES678来袭
先来一个数组
var baseArray = [1, 1, '1', '1', null, null,
undefined, undefined,
new String('1'), new String('1'),
/a/, /a/,
NaN, NaN
];
set
let unique_1 = arr => [...new Set(arr)];
// let unique_1 = arr => Array.from(new Set(arr))
console.log(unique_1(baseArray));
输出
[1, "1", null, undefined, String, String, /a/, /a/, NaN]
filter
let unique_2 = arr => {
let res = arr.filter((item, index, array) => {
return array.indexOf(item) === index; // 当前元素在数组中第一次出现则返回true
})
return res;
}
console.log(unique_2(baseArray));
输出
[1, "1", null, undefined, String, String, /a/, /a/]
这个把NaN
过滤了,因为Array.indexOf(NaN)
值为-1
reduce
let unique_3 = arr => arr.reduce((pre, cur) => pre.includes(cur) ? pre : [...pre, cur], []);
console.log(unique_3(baseArray));
输出
[1, "1", null, undefined, String, String, /a/, /a/, NaN]
原理跟普通for循环相同,先声明一个空数组,如果includes
为false
,则push
当前元素,只不过逼格高那么一丢丢丢丢
键值对
let unique_4 = arr => {
let obj = {};
return arr.filter(item => Reflect.has(obj, typeof item + item) ? false : (obj[typeof item + item] = true));
}
console.log(unique_4(baseArray))
输出
[1, "1", null, undefined, String, /a/, NaN]
从某种意义上来说,这个方法最完美
obj[typeof item + item]写法缘由:对象的key必须是字符串