2014-02-20 96 views
0

工作,我写了这个代码,但只有第一个条件是工作:如果其他条件没有在Javascript

if(document.getElementById('v').value == Infinity) { 
    //alert 
} 
else if(document.getElementById('v').value == -Infinity) { 
    //alert 
}  
else if(document.getElementById('v').value == undefined) { 
    //alert 
} 
else if(document.getElementById('v').value == isNaN) { 
    //alert 
} 

为什么不把其他条件(-InfinityundefinedisNaN)工作?

+1

如何输入无限? – elclanrs

+0

@elclanrs well'Infinity'== Infinity是真的,因为有强制发生 – axelduch

+0

如果这是OP的用例,它看起来很混乱,你会比较一个字符串。 – elclanrs

回答

1

您可以在Javascript中使用关键字throw将新的exceptions抛出(参见下面的示例)。

isNaN是一个功能

要检查一些使用的有效性:Number.NEGATIVE_INFINITYNumber.POSITIVE_INFINITY

换句话说:

if (typeof document.getElementById('v') === 'undefined' || 
    document.getElementById('v').length === 0) 
    throw new TypeError("Undefined value"); 
else if(parseInt(document.getElementById('v').value, 10) == Number.POSITIVE_INFINITY) 
    throw new RangeError("Value is too big"); 
else if(isNaN(document.getElementById('v').value)) 
    throw new TypeError("Value must be a valid number"); 

您可以获取论文例外,如:

try { 
// call your checkup function here 
} catch (exception) { 
alert ("Oh bad... Exception detected: " + exception); 
} 
+0

太棒了!现在功能:) – user3287550