2014-02-28 62 views
0

我有一個腳本行爲奇怪。如果檢查Object,Javascript isNAN返回false?

console.log (typeof button); 
console.log ('IsNAN ' + isNaN(button)); 
console.log ('isNumeric ' + jQuery.isNumeric(button)); 
console.log(); 

當按鈕是一個對象時,isNaN應該返回true;因爲對象是NaN。然而控制檯顯示方式不同:

object 
IsNAN false // should be true! 
isNumeric false 

這是爲什麼?

編輯:有問題的腳本是http://flesler-plugins.googlecode.com/files/jquery.serialScroll-1.2.2.js

線126 @函數跳轉(即按鈕)。

+0

可能重複://計算器.com/questions/2652319/how-do-you-check-that-a-number-is-nan-in-javascript) –

+1

它是一個空白對象嗎?這聽起來像'isNaN'類型轉換你的虛假對象爲0 –

+0

請注意,是NaN函數被破壞:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN#Description –

回答

3

IsNAN false // should be true!

不一定。 :-) isNaN只有在它的參數(如果必要時轉換爲Number)爲NaN時才爲真。

根據對象是什麼,當轉換爲Number時,可能是也可能不是NaN。它取決於將對象轉換爲其原始值時發生的情況。例如,null轉換爲0。在許多情況下,許多其他情況下,轉換爲原始語言包括將其轉換爲字符串(例如數組),並且某些對象的默認toString可能會返回可以轉換爲非 Number的東西。非NaN對象

實例:

// null 
console.log(Number(null));   // 0 

// an array (which becomes "23" when converted to primitive, because 
// arrays do `join` for `toString`; then the "23" becomes 23) 
console.log(Number([23]));   // 23 

// another object implementing toString or valueOf in a way that returns 
// something convertable to a non-NaN number 
console.log(Number(new Foo("47"))); // 47 

...其中Foo是:(在上述中,toString可以valueOf以及)

function Foo(value) { 
    this.value = value; 
} 
Foo.prototype.toString = function() { 
    return this.value; 
}; 

+0

哇!好的anaswer!謝謝大家。這一個似乎是最好的一個壽。 不知道isNaN首先試圖將數值轉換成數字,然後檢查它是否爲NaN。 – Grzegorz

2

isNaN ()與空對象調用預計將是假的。

如果您的對象不爲空,並且無法轉換爲數字,則它將返回true。

0

我認爲你的變量按鈕等於null。

的typeof(空)== '對象'

isNaN(空)==假

[你如何檢查一個數字是NaN在JavaScript?(HTTP的