要求输入一个数组:
var arr = [false, true, undefined, null, NaN, 0, 1, {}, {}, 'a', 'a', NaN]
输出:
[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;
}
var arr = [false, true, undefined, null, NaN, 0, 1, {}, {}, 'a', 'a', NaN]
console.log(arr.uniq()) //[false, true, undefined, null, NaN, 0, 1,{}, {}, "a"]
方法优化:
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;
}
var arr = [false, true, undefined, null, NaN, 0, 1, {}, {}, 'a', 'a', NaN]
console.log(arr.uniq()) //[false, true, undefined, null, NaN, 0, 1,{}, {}, "a"]
网友评论