我如何检查一个变量是否不是null,也不是数字

How can I check if a variable is not null and also a number?

本文关键字:是否 数字 变量 null 何检查 检查 一个      更新时间:2023-09-26

我正在使用以下内容:

$scope.option.selectedSubject != null && !isNaN($scope.option.selectedSubject)

有人能告诉我是否有其他方法可以检查变量是否是有效的定义数吗?有没有办法只需一次检查就可以做到这一点,或者我如何创建一个函数来进行检查,然后调用它?

也许这个函数可以帮助您:

function isANumber(x) {
 return ((+x)===x);
}

这可能很有用:当在脚本中的某个地方分配变量时,变量只能是null,默认情况下永远不会是null

var foo; // undefined
foo = null;
// null could be returned by a function too, which is the most common use of null

正如zzzzBov在他的评论中所说,"isNaN将检查该值的数字表示是否为NaN。这意味着isNaN('500')false,而isNaN('foo')true。"

要回答您的问题,请查看以下表格:

!isNaN(undefined); // false
!isNaN(null); // true
!isNaN(); // false
!isNaN(''); // true <= Watch out for this one !
!isNaN('test'); // false
!isNaN('10'); // true
!isNaN(10); // true

如果你想确保它是一个数字,你应该使用typeof,如果这是一个字符串,请检查它是否有长度。将这一切封装在一个函数中会创建类似于:

function isNumber (num) {
    // Return false if num is null or an empty string
    if (num === null || (typeof num === "string" && num.length === 0)) {
        return false;
    }
    return !isNaN(num);
}
isNumber(undefined); // false
isNumber(null); // false
isNumber(); // false
isNumber(''); // false
isNumber('test'); // false
isNumber('10'); // true
isNumber(10); // true

如果你只关心数字表示,这就足够了。

!isNaN($scope.option.selectedSubject + "")

注意+ ""