JS数组去重(含NaN)
NaN是一个比较特殊的值,它和任何值作比较都会返回false(包括它自身),NaN == NaN 会返回false
当使用indexOf()方法去重时,遇到两个NaN时会认为两个值不相等,因此不会返回-1,导致无法去重NaN
下面是自己写的代码,呃…感觉很菜…
Array.prototype.uniq = function () {
var newArr = []
for (var i = 0; i < this.length; i++) {
if (!(typeof this[i] === 'number' && isNaN(this[i]))) {
//当前值不为NaN
if (newArr.indexOf(this[i]) == -1) {
newArr.push(this[i])
}
}
else {
//当前值为NaN
var flag = 1
for (var j = 0; j < newArr.length; j++) {
if (typeof newArr[j] === 'number' && isNaN(newArr[j])) {
flag = 0
break
}
}
if (flag) {
newArr.push(this[i])
}
}
}
return newArr
}
var a = [true, false, null, undefined, NaN, 0, 1, {}, {}, 'a', 'a', NaN]
console.log(a.uniq())
在牛客上看其他大牛写的,如下
Array.prototype.uniq = function () {
var newArr = []
var flag = true
for (var i = 0; i < this.length; i++) {
if (newArr.indexOf(this[i]) == -1) {
if (this[i] != this[i]) { //当前元素为NaN
if (flag) { //newArr中不存在NaN
newArr.push(this[i])
flag = false
}
}
else {
newArr.push(this[i])
}
}
}
return newArr
}
var a = [true, false, null, undefined, NaN, 0, 1, {}, {}, 'a', 'a', NaN]
console.log(a.uniq())
两个综合了一下
Array.prototype.uniq = function () {
var newArr = []
var flag = true
for (var i = 0; i < this.length; i++) {
if (this[i] == this[i]) {
//当前值不为NaN
if (newArr.indexOf(this[i]) == -1) {
newArr.push(this[i])
}
}
else {
//当前值为NaN
if (flag) {
//newArr中没有NaN
newArr.push(this[i])
flag = false
}
}
}
return newArr
}
var a = [true, false, null, undefined, NaN, 0, 1, {}, {}, 'a', 'a', NaN]
console.log(a.uniq())