简体   繁体   English

检查数组是否包含数字(问题为0)

[英]Checking if array contains a number (Issue with 0)

I have an array of numbers. 我有一个数字数组。 The array may contain a zero. 该数组可以包含零。

How can I check if the array contains a number or not? 如何检查数组是否包含数字? I am currently doing that: 我目前正在这样做:

if (Number(arr. value(pos)) != false)

This however, considers 0 as false too. 但是,这也将0视为假。 So if a 0 is in the array, it will consider it as if the array was empty. 因此,如果数组中为0,则它​​将视为数组为空。

How can I overcome this? 我该如何克服?

Try this: 尝试这个:

if (Number(arr. value(pos)) !== false)

!= does a "falsy" check. !=进行“虚假”检查。 0, undefined, false, null, '', and NaN are all falsy. 0, undefined, false, null, '',NaN都是虚假的。 Everything else is "truthy". 其他一切都是“真实的”。 If you want to test for false only (and not all other falsy statements) you have to use === or !== . 如果只想测试false(而不是所有其他虚假语句),则必须使用===!== Try to avoid != and == , because most if the time you actually mean !== and === 尽量避免!=== ,因为大多数情况下,如果您实际上是指!=====

koenp's answer is perfectly correct, but if (!isNaN(arr. value(pos))) might be preferable in this case. koenp的答案是完全正确的,但是在这种情况下, if (!isNaN(arr. value(pos))) arr。value if (!isNaN(arr. value(pos)))可能更可取。 Also, it may be a notch faster. 同样,它可能会更快。 http://www.w3schools.com/jsref/jsref_isnan.asp http://www.w3schools.com/jsref/jsref_isnan.asp

might be a solution. 可能是一个解决方案。 It checks whether the Number is bigger than Zero. 它检查数字是否大于零。

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

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