我只是创建一个函数,该函数将 JSON.stringify
输入,同时也会检测数字输入上的 NaN
,但不想使用 loại
由于以下原因。输入可以是数字
, bool 值
hoặc字符串
。仅此而已。
我已经遇到了 NaN !== NaN
的情况,所以:
if (input !== input || input === Infinity || input === -Infinity) {
output = input.toString();
} khác {
output = JSON.stringify(input);
}
我这样做是因为当值为 NaN
hoặc giờ,JSON.stringify()
trở lại "null"
无穷大
.
我知道使用 loại
Và toString()
这很容易实现,但一些性能测试表明 loại
在 IE11 下是非常慢(在我们的情况下比 JSON.stringify()
慢 4-5 倍),我们需要在这里关注 IE11。
我想知道是否还有更多 val !== val
的情况。
这里有一个性能测试:https://jsperf.com/typeof-vs-nan-nan2没有使用 SO ,因为它们似乎在服务器端运行代码,因为那里的 IE 性能与其他地方一样好。不可能的事情。
本地测试是:
var mockdata = [];
function notToJson(val) {
return val !== val || val === Infinity || val === -Infinity;
}
for (var i = 0; i < 500000; i++) {
var n = Math.floor(Math.random()*1000000);
if (Math.random()>0.5) {
n = n.toString();
} else if (Math.random()>0.5) {
if (Math.random()>0.5) {
n = NaN;
} khác {
if (Math.random()>0.5) {
n = Infinity;
} khác {
n = -Infinity;
}
}
}
mockdata.push(n);
}
console.time("typeof");
for (i = 0; i < 500000; i++) {
var res = typeof mockdata[i] === "string";
}
console.timeEnd("typeof");
console.time("notToJson");
for (i = 0; i < 500000; i++) {
res = notToJson(mockdata[i]);
}
console.timeEnd("notToJson");
console.time("toString");
for (i = 0; i < 500000; i++) {
res = mockdata[i].toString();
}
console.timeEnd("toString");
console.time("JSON.stringify");
for (i = 0; i < 500000; i++) {
res = JSON.stringify(mockdata[i]);
}
console.timeEnd("JSON.stringify");
console.time("Full typeof");
for (i = 0; i < 500000; i++) {
res = typeof mockdata[i]==="string"?JSON.stringify(mockdata[i]):mockdata[i].toString();
}
console.timeEnd("Full typeof");
console.time("Full notToJson");
for (i = 0; i < 500000; i++) {
res = notToJson(mockdata[i])?mockdata[i].toString():JSON.stringify(mockdata[i]);
}
console.timeEnd("Full notToJson");
Chrome 输出为:
但是 IE11 输出是:
我注意到 mockdata
的字符串越少,loại
的性能显着提高(谈论 IE11)。
以下是 val !== val
返回 true 的一些情况:
console.log({} !== {}); // true
console.log(new Date() !== new Date()); // true
console.log(new String("") !== new String("")); // true
这只适用于对象不同的情况:
var a = b = {}; // now they are equal
console.log(a !== b); // false
Symbols 也会发生这种情况(ES6 功能):
console.log(Symbol() !== Symbol()); // true
Tôi là một lập trình viên xuất sắc, rất giỏi!