2017-02-20 71 views
0

我只是創建一個函數,將JSON.stringify輸入,但也檢測NaN數字輸入,但不想使用typeof由於下述原因。輸入可以是number,booleanstring。而已。在哪種情況下val!== val?

我已經達到了情況NaN !== NaN,所以:

if (input !== input || input === Infinity || input === -Infinity) { 
    output = input.toString(); 
} else { 
    output = JSON.stringify(input); 
} 

我做這種方式,因爲JSON.stringify()回報"null"當值NaNInfinity

我知道,與typeoftoString()這是很容易實現,但一些性能測試表明,typeof IE11下是很慢(比JSON.stringify()慢4-5倍,我們的情況下),我們需要把重點放在IE11這裏。

我想知道是否有更多的案例val !== val

在這裏你有一個性能測試:https://jsperf.com/typeof-vs-nan-nan2 沒有使用的SO之一,因爲他們似乎運行的代碼服務器端,因爲那裏的IE性能是一樣好的地方。 Impossibru的事情。

本地測試:

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; 
     } else { 
      if (Math.random()>0.5) { 
       n = Infinity; 
      } else { 
       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的輸出是:

enter image description here

但IE11輸出爲:

enter image description here

我已經注意到,少串mockdata已經,typeof的性能顯着提高(談論IE11)。

+0

*但由於原因*不想使用typeof,原因是什麼? –

+1

原因是它在IE11中很慢,因爲你可以在這個問題中讀到。 – Aloso

+0

'{}!== {}'這是我唯一能夠想到的其他東西,其中'val!== val' – George

回答

2

這裏有一些情況下,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 
+0

完美。正是我需要的。 –

相關問題