Array.includes 检查 NaN 的 Polyfill
Polyfill for Array.includes checking NaN
所以首先这不是我面临的问题。当我遇到 .indexOf and .includes
的 Array 原型方法时,我正在浏览一些 Javascript
博客。因此,如果一个数组的值是 NaN
,那么 indexOf
可能无法计算出来,我只能使用 .includes
。但我的问题是,由于 includes
的浏览器兼容性实际上不包括 IE,那么检测 NaN 检查的替代方法应该是什么?我想通过参考 this
来构造一个 polyfill
if (Array.prototype.includes) {
Object.defineProperty(Array.prototype, "includes", {
enumerable: false,
value: function(obj) {
var newArr = this.filter(function(el) {
return el == obj;
});
return newArr.length > 0;
}
});
}
var arr = [NaN];
console.log(arr.includes(NaN));
但不幸的是,它也返回 false。那么我还有什么其他选择?还是我遗漏了什么?
您也可以为 Number.isNaN
添加一个 polyfill,然后在 filter
测试中使用它 - 如果 obj
和 el
都通过了 Number.isNaN
,然后 return 真:
Number.isNaN = Number.isNaN || function(value) {
return value !== value;
}
// if (!Array.prototype.includes) {
Object.defineProperty(Array.prototype, "includes", {
enumerable: false,
value: function(obj) {
var newArr = this.filter(function(el) {
return el == obj || Number.isNaN(el) && Number.isNaN(obj);
});
return newArr.length > 0;
}
});
// }
var arr = [NaN];
console.log(arr.includes(NaN));
Array#includes
使用Same-Value-Zero算法,与==
.
不相同
Same-Value由Object.is()
提供,您可以手动检查-0
和+0
以获得检查的“-0”部分。
链接的页面包含一个 polyfill,尽管由于 polyfill 包含一个使 -0
和 +0
不同的步骤 - 你不希望在 Same-Value-Zero 算法中 - 你可以将其省略并相应地简化:
function SameValueZero(x, y) {
return x === y || (x !== x && y !== y);
}
您可以使用 firstIndex
找到 NaN
的索引。像这样尝试。
var arr = [NaN];
let index = arr.findIndex(Number.isNaN)
console.log(index >= 0);
所以首先这不是我面临的问题。当我遇到 .indexOf and .includes
的 Array 原型方法时,我正在浏览一些 Javascript
博客。因此,如果一个数组的值是 NaN
,那么 indexOf
可能无法计算出来,我只能使用 .includes
。但我的问题是,由于 includes
的浏览器兼容性实际上不包括 IE,那么检测 NaN 检查的替代方法应该是什么?我想通过参考 this
if (Array.prototype.includes) {
Object.defineProperty(Array.prototype, "includes", {
enumerable: false,
value: function(obj) {
var newArr = this.filter(function(el) {
return el == obj;
});
return newArr.length > 0;
}
});
}
var arr = [NaN];
console.log(arr.includes(NaN));
但不幸的是,它也返回 false。那么我还有什么其他选择?还是我遗漏了什么?
您也可以为 Number.isNaN
添加一个 polyfill,然后在 filter
测试中使用它 - 如果 obj
和 el
都通过了 Number.isNaN
,然后 return 真:
Number.isNaN = Number.isNaN || function(value) {
return value !== value;
}
// if (!Array.prototype.includes) {
Object.defineProperty(Array.prototype, "includes", {
enumerable: false,
value: function(obj) {
var newArr = this.filter(function(el) {
return el == obj || Number.isNaN(el) && Number.isNaN(obj);
});
return newArr.length > 0;
}
});
// }
var arr = [NaN];
console.log(arr.includes(NaN));
Array#includes
使用Same-Value-Zero算法,与==
.
Same-Value由Object.is()
提供,您可以手动检查-0
和+0
以获得检查的“-0”部分。
链接的页面包含一个 polyfill,尽管由于 polyfill 包含一个使 -0
和 +0
不同的步骤 - 你不希望在 Same-Value-Zero 算法中 - 你可以将其省略并相应地简化:
function SameValueZero(x, y) {
return x === y || (x !== x && y !== y);
}
您可以使用 firstIndex
找到 NaN
的索引。像这样尝试。
var arr = [NaN];
let index = arr.findIndex(Number.isNaN)
console.log(index >= 0);