javascript 检查数组是否包含(仅)数值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32817027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:46:59  来源:igfitidea点击:

Check if an array contains (only) numeric values

javascriptarrays

提问by user2361134

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_Intshould be considered as (purely) numeric.
  • arrayVal_Alphaand arrayVal_AlphaNumericshould be considered as strings.
  • 以上arrayVal_Int应被视为(纯)数字。
  • arrayVal_Alpha并且arrayVal_AlphaNumeric应该被视为字符串。

I need to check that in JavaScript.

我需要在 JavaScript 中检查它。

回答by Touffy

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

最短的解决方案,true当且仅当每个项目都是(强制为)一个数字时才求值:

!yourArray.some(isNaN)

回答by A.T.

Using simple JavaScript, you can do something like this:

使用简单的 JavaScript,您可以执行以下操作:

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

It will return true;

它会返回真;

回答by aztlan2k

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.

感谢@Touffy,您的建议。

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

回答by Prawin soni

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