cuốn sách gpt4 ai đã làm

javascript - 在什么情况下 val !== val? (将变量与其自身进行比较)

In lại Tác giả: Walker 123 更新时间:2023-11-28 18:07:19 27 4
mua khóa gpt4 Nike

我只是创建一个函数,该函数将 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ạitoString() 这很容易实现,但一些性能测试表明 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 输出为:

nhập mô tả hình ảnh ở đây

但是 IE11 输出是:

nhập mô tả hình ảnh ở đây

我注意到 mockdata 的字符串越少,loại 的性能显着提高(谈论 IE11)。

câu trả lời hay nhất

以下是 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

关于javascript - 在什么情况下 val !== val? (将变量与其自身进行比较),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42345499/

27 4 0
Walker 123
Hồ sơ

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá taxi Didi miễn phí
Phiếu giảm giá taxi Didi
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress