我只在Firefox的JavaScript控制台中尝试过,但以下语句都没有返回true:
parseFloat('geoff') == NaN;
parseFloat('geoff') == Number.NaN;
我只在Firefox的JavaScript控制台中尝试过,但以下语句都没有返回true:
parseFloat('geoff') == NaN;
parseFloat('geoff') == Number.NaN;
当前回答
我只想分享另一种选择,它不一定比这里的其他选择更好,但我认为它值得一看:
function customIsNaN(x) { return (typeof x == 'number' && x != 0 && !x); }
这背后的逻辑是,除了0和NaN之外的所有数字都被转换为true。
我做了一个快速测试,它的性能和Number一样好。isNaN和as检查自身是否为false。这三个都比isNan表现得好
结果
customIsNaN(NaN); // true
customIsNaN(0/0); // true
customIsNaN(+new Date('?')); // true
customIsNaN(0); // false
customIsNaN(false); // false
customIsNaN(null); // false
customIsNaN(undefined); // false
customIsNaN({}); // false
customIsNaN(''); // false
如果您想避免损坏的isNaN函数,可能会很有用。
其他回答
我创建了这个小函数,它就像一个咒语。 而不是检查NaN,这似乎是违反直觉的,你检查一个数字。我很确定我不是第一个这样做的人,但我想分享一下。
function isNum(val){
var absVal = Math.abs(val);
var retval = false;
if((absVal-absVal) == 0){
retval = true
}
return retval;
}
NaN是一个特殊的值,不能这样测试。我想和大家分享一个有趣的事情
var nanValue = NaN;
if(nanValue !== nanValue) // Returns true!
alert('nanValue is NaN');
这只对NaN值返回true,是一种安全的测试方式。肯定应该被包装在一个函数中,或者至少被注释,因为测试相同的变量是否彼此不相等显然没有多大意义,呵呵。
marksyzm的答案工作得很好,但它不会为无穷大返回false,因为无穷大在技术上不是一个数字。
我想出了一个isNumber函数来检查它是否是一个数字。
函数isNumber(i) isNaN(i && i !== true ?编号(i): parseFloat(i)) &&[编号。POSITIVE_INFINITY, Number.NEGATIVE_INFINITY].indexOf(i) == -1; } console.log (isNumber(∞)); console.log (isNumber(“asdf ")); console.log (isNumber (1.4)); console.log (isNumber(南)); console.log (isNumber (Number.MAX_VALUE)); console.log (isNumber (" 1.68 "));
更新: 我注意到这段代码在某些参数上失败了,所以我改进了它。
function isNumber(i) {//function for checking if parameter is number if(!arguments.length) { throw new SyntaxError("not enough arguments."); } else if(arguments.length > 1) { throw new SyntaxError("too many arguments."); } else if([Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY].indexOf(i) !== -1) { throw new RangeError("number cannot be \xB1infinity."); } else if(typeof i === "object" && !(i instanceof RegExp) && !(i instanceof Number) && !(i === null)) { throw new TypeError("parameter cannot be object/array."); } else if(i instanceof RegExp) { throw new TypeError("parameter cannot be RegExp."); } else if(i == null || i === undefined) { throw new ReferenceError("parameter is null or undefined."); } else { return !isNaN(i && i !== true ? Number(i) : parseFloat(i)) && (i === i); } } console.log(isNumber(Infinity)); console.log(isNumber(this)); console.log(isNumber(/./ig)); console.log(isNumber(null));
也许还有这个:
function isNaNCustom(value){
return value.toString() === 'NaN' &&
typeof value !== 'string' &&
typeof value === 'number'
}
虽然@chiborg的回答是正确的,但还有更多需要注意的地方:
parseFloat('1.2geoff'); // => 1.2
isNaN(parseFloat('1.2geoff')); // => false
isNaN(parseFloat('.2geoff')); // => false
isNaN(parseFloat('geoff')); // => true
重点是,如果你使用这个方法来验证输入,结果将是相当自由的。
所以,是的,你可以使用parseFloat(string)(或在完整数字的情况下parseInt(string, radix)',然后随后用isNaN()包装它,但要注意数字与其他非数字字符交织在一起的问题。