for循環?NONONOjavascript
先來一個數組java
var baseArray = [1, 1, '1', '1', null, null, undefined, undefined, new String('1'), new String('1'), /a/, /a/, NaN, NaN ];
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]
let unique_2 = arr => { let res = arr.filter((item, index, array) => { return array.indexOf(item) === index; // 當前元素在數組中第一次出現則返回true }) return res; } console.log(unique_2(baseArray));
輸出code
[1, "1", null, undefined, String, String, /a/, /a/]
這個把NaN
過濾了,由於Array.indexOf(NaN)
值爲-1對象
let unique_3 = arr => arr.reduce((pre, cur) => pre.includes(cur) ? pre : [...pre, cur], []); console.log(unique_3(baseArray));
輸出ip
[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))
輸出it
[1, "1", null, undefined, String, /a/, NaN]
從某種意義上來講,這個方法最完美console
obj[typeof item + item]寫法原因:對象的key必須是字符串