簡體   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