我只在Firefox的JavaScript控制台中尝试过,但以下语句都没有返回true:
parseFloat('geoff') == NaN;
parseFloat('geoff') == Number.NaN;
我只在Firefox的JavaScript控制台中尝试过,但以下语句都没有返回true:
parseFloat('geoff') == NaN;
parseFloat('geoff') == Number.NaN;
当前回答
发现这很有用
// Long-hand const isFalsey = (value) => { if (
value === null ||
value === undefined ||
value === 0 ||
value === false ||
value === NaN ||
value === "" ) {
return true; } return false; };
// Short-hand const
isFalsey = (value) => !value;
其他回答
两种都试试看
if(isNaN(parseFloat('geoff')) && typeof(parseFloat('geoff')) === "number");
//true
我创建了这个小函数,它就像一个咒语。 而不是检查NaN,这似乎是违反直觉的,你检查一个数字。我很确定我不是第一个这样做的人,但我想分享一下。
function isNum(val){
var absVal = Math.abs(val);
var retval = false;
if((absVal-absVal) == 0){
retval = true
}
return retval;
}
Number('hello').toString() === 'NaN' // true
Number(undefined).toString() === 'NaN' // true
Number('12345').toString() === 'NaN' // false
// These all evaluate to 0 which is a number
Number('').toString() === 'NaN' // false // 0
Number('0').toString() === 'NaN' // false // 0
Number().toString() === 'NaN' // false // 0
// These all evaluate to 0 and 1 which is a number
Number(false).toString() === 'NaN' // false // 0
Number(true).toString() === 'NaN' // false // 1
我使用下划线的isNaN函数,因为在JavaScript中:
isNaN(undefined)
-> true
至少,要意识到这一点。
如果您的环境支持ECMAScript 2015,那么您可能需要使用Number。isNaN来确保这个值真的是NaN。
isNaN的问题是,如果你将它用于非数值数据,就会应用一些令人困惑的规则(根据MDN)。例如,
isNaN(NaN); // true
isNaN(undefined); // true
isNaN({}); // true
因此,在ECMA Script 2015支持的环境中,您可能希望使用
Number.isNaN(parseFloat('geoff'))