实例:为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;
}
就是上面else里的代码块,我不是很理解。谢谢大家!
https://blog.csdn.net/weixin_41475710/article/details/82876573