繁体   English   中英

检查值是否为数字做某事

[英]check if value is numeric do something

我正在尝试使用以下脚本检查传递的值是字符串还是数字

$scope.checkval=function(res){
    console.log(res.profile_id)
    if(angular.isNumber(res.profile_id)){
        console.log('Number');
     }else {
        console.log('Center Code is not a number');
     }
}

从上面的代码中,我总是得到Center code is not a number ,尽管传递的值是数字

该API不用于检查字符串是否为数字。 它正在检查该值是否已经是一个数字。

最简单的方法是使用+一元运算符将值强制为数字,然后使用!isNaN()验证它实际上是可解析的数字字符串。

$scope.checkval = function(n) {
  return !isNaN(+n);
};

当值可以转换为实际数字时,它将返回true 请注意,常数NaN也是一个数字,但是您可能不希望在“数字”的定义中包括NaN

isNumber是一个非常准确的函数,因此我个人认为您传递的值可能是字符串。 但是为了避免该潜在问题,您可以执行此操作,这将消除字符串为数字的可能性,但不能纠正不是字符串的可能性。

$scope.checkval = function(res){
    //unary operator will convert the string into a number if appropriate
    var numberToCheck = +res;
    if (angular.isNumber(numberToCheck)) {
        console.log('Number');
     } else {
        console.log('Center Code is not a number');
     }
}

如果您不想/不能使用内置函数的角度,Pointy的解决方案是更好的解决方案

是像“ 5”或“ 5”那样传递变量。

res.profile_id = 5; //would come out as true

res.profile_id = '5'; //would come out as false

res.profile_id可能实际上是一个字符串。

如果期望它是一个整数(例如,如果它是从数据库返回的主键),则可以使用以下命令将其显式转换为int:

res.profile_id = parseInt(res.profile_id, 10);

如果这是用户输入字段,或者响应中可能有文本,则可以像这样测试它:

if (!isNaN(res.profile_id){
    ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM