- ===:严格判断类型和值、NaN自身不想等
- indexOf:底层也是使用
===
。严格判断类型和值,NaN自身不想等 - map和set:NaN相等
var str1 = '1';
var str2 = new String('1');
console.log(str1 == str2); // true
console.log(str1 === str2); // false
console.log(null == null); // true
console.log(null === null); // true
console.log(undefined == undefined); // true
console.log(undefined === undefined); // true
console.log(NaN == NaN); // false
console.log(NaN === NaN); // false
console.log(/a/ == /a/); // false
console.log(/a/ === /a/); // false
console.log({} == {}); // false
console.log({} === {}); // false
new Set([NaN, NaN]) // NaN
typeof new String('1') // object
Object.prototype.toString.call('1') // [object String]
Object.prototype.toString.call(new String('1')) // [object String]
方法 | 不相等 |
---|---|
=== | 相同复杂类型、NaN |
indexOf | 相同复杂类型、NaN |
Set、Map | 相同复杂类型 |
复杂类型:Object、Array、Date、RegExp、Error(可以检测function)
结论:凡事使用 ===
或者 indexOf
都会导致相同复杂类型、NaN不能去重,Set、Map可以判断相同NaN
解决:类型+值转为字符串来判断
全部去重
var array = [1, 1, '1', '1', null, null, undefined, undefined, new String('1'), new String('1'), /a/, /a/, NaN, NaN];
function unique(array) {
var obj = {};
return array.filter(function(item, index, array){
var key = typeof item + JSON.stringify(item)
return obj.hasOwnProperty(key) ? false : (obj[key] = true)
})
}
unique(array)
// [1, "1", null, undefined, String, /a/, NaN]