浅谈Object.prototype.toString.call()方法
该文章疑惑点解析:
引用:
- 实例:为Array对象添加一个去除重复项的方法
input
[false, true, undefined, null, NaN, 0, 1, {}, {}, 'a', 'a', NaN].uniq()
output
[false, true, undefined, null, NaN, 0, 1, {}, {}, 'a']
这里要注意,NaN === NaN 为false,{} === {}为false。
Array.prototype.uniq = function () {
if (!this.length || this.length == 0) return this;
var res = [], key, hasNaN = false, temp = {};
for (var i = 0 ; i < this.length; i++) {
if (typeof this[i] === 'object') {
res.push(this[i]);
} else if (this[i] != this[i]) { // 如果当前遍历元素是NaN
if (!hasNaN) {
res.push(this[i]);
hasNaN = true;
}
} else {
key = typeof(this[i]) + this[i];
if (!temp[key]) {
res.push(this[i]);
temp[key] = true;
}
}
}
return res;
}
另一种解法:
Array.prototype.uniq = function () {
var res = [];
var flag = true;
this.forEach(function(x) {
if (res.indexOf(x) == -1) {
if (x != x) {
if (flag) {
res.push(x);
flag = false;
}
} else {
res.push(x);
}
}
})
return res;
}
另一种解法解析
- 这里是针对于NaN,push第一个出现的NaN
if (x != x) {
if (flag) {
res.push(x);
flag = false;
}
}
- 这里是针对{}和其他,push{}和其他
else { res.push(x); }
-
关于{}!={}
- -
{}!={} 单纯这样子平常调试是true;
但是在里forEach面的话判断的是同一个{},所以forEach里面{}=={},{}!={}是false
所以{}执行的是 else {
res.push(x);
}
;
而NaN执行的是
if (x != x) {
if (flag) {
res.push(x);
flag = false;
}
}