如何检查JavaScript是否在某个数组索引处存在值?

这将用于测试位置“索引”处的值是否存在或是否有更好的方法:

if(arrayName[index]==""){
     // do stuff
}
前端飞云2020/03/12 16:40:03

To check if it has never been defined or if it was deleted:

if(typeof arrayName[index]==="undefined"){
     //the index is not in the array
}

also works with associative arrays and arrays where you deleted some index

To check if it was never been defined, was deleted OR is a null or logical empty value (NaN, empty string, false):

if(typeof arrayName[index]==="undefined"||arrayName[index]){
     //the index is not defined or the value an empty value
}
神乐Harry2020/03/12 16:40:03

I ran into this issue using laravel datatables. I was storing a JSON value called properties in an activity log and wanted to show a button based on this value being empty or not.

Well, datatables was interpreting this as an array if it was empty, and an object if it was not, therefore, the following solution worked for me:

render: function (data, type, full) {
    if (full.properties.length !== 0) {
        // do stuff
    }
}

An object does not have a length property.

神奇飞云2020/03/12 16:40:03

try this if array[index] is null

if (array[index] != null) 
MandyJinJin路易2020/03/12 16:40:03

I would like to point out something a few seem to have missed: namely it is possible to have an "empty" array position in the middle of your array. Consider the following:

let arr = [0, 1, 2, 3, 4, 5]

delete arr[3]

console.log(arr)      // [0, 1, 2, empty, 4, 5]

console.log(arr[3])   // undefined

The natural way to check would then be to see whether the array member is undefined, I am unsure if other ways exists

if (arr[index] === undefined) {
  // member does not exist
}
凯老丝2020/03/12 16:40:03
if(arrayName.length > index && arrayName[index] !== null) {
    //arrayName[index] has a value
}
米亚GO2020/03/12 16:40:03
if(!arrayName[index]){
     // do stuff
}
路易GO2020/03/12 16:40:03

仅使用.length不安全,并且会在某些浏览器中导致错误。这是一个更好的解决方案:

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

或者,我们可以使用:

Object.keys(__array__).length
小哥GOItachi2020/03/12 16:40:03

我们不能只是这样做:

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