How do I check in JavaScript if a value exists at a certain array index?

这是否会用于测试位置“index”处的值是否存在,还是有更好的方法:

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

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.

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
}

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 .

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

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

or

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

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

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

我们不能这样做:

if(arrayName.length > 0){   
    //or **if(arrayName.length)**
    //this array is not empty 
}else{
   //this array is empty
}

Using only .length is not safe and will cause an error in some browsers. Here is a better solution:

if(array && array.length){   
   // not empty 
} else {
   // empty
}

or, we can use:

Object.keys(__array__).length
链接地址: http://www.djcxy.com/p/78908.html

上一篇: 无法从android.support.v4.app.Fragment转换为android.app.Fragment

下一篇: 如果某个数组索引中存在值,我该如何检查JavaScript?