Check if an array contains (only) numeric values

2020-02-23 08:38发布

I have arrays such as

var arrayVal_Int = ["21", "53", "92", "79"];   
var arrayVal_Alpha = ["John", "Christine", "Lucy"];  
var arrayVal_AlphaNumeric = ["CT504", "AP308", "NK675"];
  • Above arrayVal_Int should be considered as (purely) numeric.
  • arrayVal_Alpha and arrayVal_AlphaNumeric should be considered as strings.

I need to check that in JavaScript.

4条回答
淡お忘
2楼-- · 2020-02-23 08:51

Try this:

let x = [1,3,46,7,7,8];
let y = [1,354,"fg",4];
let z = [1, 3, 4, 5, "3"];

isNaN(x.join("")) // false
isNaN(y.join("")) // true
isNaN(z.join("")) // false
查看更多
对你真心纯属浪费
3楼-- · 2020-02-23 08:52

I had a similar need but wanted to verify if a list contained only integers (i.e., no decimals). Based on the above answers here's a way to do that, which I posting in case anyone needs a similar check.

Thanks @Touffy, for your suggestion.

let x = [123, 234, 345];
let y = [123, 'invalid', 345];
let z = [123, 234.5, 345];

!x.some(i => !Number.isInteger(i))  // true
!y.some(i => !Number.isInteger(i))  // false
!z.some(i => !Number.isInteger(i))  // false
查看更多
The star\"
4楼-- · 2020-02-23 08:55

Using simple JavaScript, you can do something like this:

var IsNumericString = ["21","53","92","79"].filter(function(i){
    return isNaN(i);
}).length > 0;

It will return true;

查看更多
何必那么认真
5楼-- · 2020-02-23 08:59

Shortest solution, evals to true if and only if every item is (coercible to) a number:

!yourArray.some(isNaN)
查看更多
登录 后发表回答