在JavaScript中,判断一个值是否不能为数字通常使用isNaN()
函数或者Number.isNaN()
方法。这两个方法都可以用来检测一个值是否是非数字(Not-A-Number),但它们之间有一些差异。
isNaN()
函数isNaN()
是一个全局函数,它会尝试将传入的值转换为数字,然后再判断转换后的值是否为NaN。
isNaN('Hello'); // true,因为'Hello'转换为数字是NaN
isNaN('123'); // false,因为'123'转换为数字是123
isNaN({}); // true,因为对象转换为数字是NaN
isNaN()
的一个特点是它会进行类型转换,这意味着如果传入的值不是数字,它会尝试将其转换为数字,这可能会导致一些意想不到的结果。
Number.isNaN()
方法Number.isNaN()
是ES6引入的一个方法,它不会进行类型转换,只有当传入的值严格等于NaN时才会返回true。
Number.isNaN('Hello'); // false,因为'Hello'不是一个NaN值
Number.isNaN(NaN); // true,因为传入的值就是NaN
Number.isNaN({}); // false,因为{}不是一个NaN值
在实际应用中,如果你想要严格判断一个值是否是NaN,而不关心它的类型转换结果,应该使用Number.isNaN()
。如果你想要在转换类型后判断值是否为NaN,可以使用isNaN()
。
下面是一个使用Number.isNaN()
来判断变量是否不能为数字的示例:
function checkNotNumber(value) {
if (Number.isNaN(value)) {
console.log('The value is NaN and cannot be a number.');
} else {
console.log('The value is a number or can be converted to a number.');
}
}
checkNotNumber(NaN); // The value is NaN and cannot be a number.
checkNotNumber('123'); // The value is a number or can be converted to a number.
checkNotNumber('Hello'); // The value is a number or can be converted to a number.
checkNotNumber(undefined); // The value is a number or can be converted to a number. (因为undefined转换为数字是NaN,但是Number.isNaN(undefined)返回false)
注意,undefined
转换为数字会得到NaN
,但是Number.isNaN(undefined)
返回false
,因为undefined
本身并不是NaN
。如果你想要检测一个值是否不能转换为数字,你可以结合使用isNaN()
和Number.isNaN()
:
function checkCannotBeNumber(value) {
if (isNaN(value) && Number.isNaN(Number(value))) {
console.log('The value cannot be converted to a number.');
} else {
console.log('The value is a number or can be converted to a number.');
}
}
checkCannotBeNumber(undefined); // The value cannot be converted to a number.
在这个例子中,Number(value)
尝试将值转换为数字,然后Number.isNaN()
检查转换结果是否为NaN
。如果两个条件都满足,那么这个值就不能被转换为数字。
领取专属 10元无门槛券
手把手带您无忧上云