I'm trying to check if a value passed is either a string or a number with the below script
$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');
}
}
from the above code i'm always getting Center code is not a number
, though the value passed is numeric
That API is not for checking to see if a string is a number; it's checking to see whether the value already is a number.
The simplest thing to do is use the +
unary operator to coerce the value to be a number, and then use !isNaN()
to verify that it was in fact a parseable numeric string.
$scope.checkval = function(n) {
return !isNaN(+n);
};
That'll return true
when the value can be converted to an actual number. Note that the constant NaN
is also a number, but you probably don't want to include NaN
in your definition of "numeric".
isNumber
is a pretty accurate function so I personally would believe that the value you are passing is probably a string. But in order to avoid that potential issue you can do this, it will eliminate the potential for a string thats a number, but not correct a string that is not.
$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's solution is a much better way to go about it if you don't want to/can't use the angular built in functions
是像“ 5”或“ 5”那样传递变量。
res.profile_id = 5; //would come out as true
res.profile_id = '5'; //would come out as false
It is likely that res.profile_id is actually a string.
if you are expecting it to be an integer (like if it is a primary key coming back from the DB), you can caste it explicitly to an int by using:
res.profile_id = parseInt(res.profile_id, 10);
If this is a user input field or it is likely that there would be text in the response, you can test for it like so:
if (!isNaN(res.profile_id){
...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.