如果某个数组索引中存在某个值,如何检入JavaScript?

问题描述:

这是否可以用于测试位置index的值是否存在,或者是否有更好的方法:

Will this work for testing whether a value at position "index" exists or not, or is there a better way:

if(arrayName[index]==""){
     // do stuff
}


JavaScript中的所有数组都包含 array.length 元素,以 array [0]开头直到 array [array.length - 1] 。根据定义,如果 i 介于 i 的数组元素将被视为数组的一部分$ c> 0 和 array.length - 1 包含。

All arrays in JavaScript contain array.length elements, starting with array[0] up until array[array.length - 1]. By definition, an array element with index i is said to be part of the array if i is between 0 and array.length - 1 inclusive.

即JavaScript数组是线性的,从零开始并达到最大值,并且数组没有从数组中排除某些值或范围的机制。要确定给定位置索引(索引是0还是正整数)中是否存在值,您只需使用

That is, JavaScript arrays are linear, starting with zero and going to a maximum, and arrays don't have a mechanism for excluding certain values or ranges from the array. To find out if a value exists at a given position index (where index is 0 or a positive integer), you literally just use

if (index < array.length) {
  // do stuff
}

但是, 可能使某些数组值为null, undefined NaN Infinity ,0或一大堆不同的值。例如,如果通过增加 array.length 属性来添加数组值,则任何新值都将为 undefined

However, it is possible for some array values to be null, undefined, NaN, Infinity, 0, or a whole host of different values. For example, if you add array values by increasing the array.length property, any new values will be undefined.

确定给定值是有意义的还是已经定义的。也就是说, 未定义,或 null

To determine if a given value is something meaningful, or has been defined. That is, not undefined, or null:

if (typeof array[index] !== 'undefined') {

if (typeof array[index] !== 'undefined' && array[index] !== null) {

有趣的是,由于JavaScript的比较规则,我的最后一个例子可以优化到这个:

Interestingly, because of JavaScript's comparison rules, my last example can be optimised down to this:

if (array[index] != null) {
  // The == and != operators consider null equal to only null or undefined
}