这将用于测试一个值在位置索引是否存在,或者有更好的方法:

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

当前回答

我们就不能这样做吗

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

其他回答

检查它是否从未被定义或是否被删除:

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

也适用于关联数组和删除某些索引的数组

要检查它是否从未被定义,was deleted OR是一个空值或逻辑空值(NaN,空字符串,false):

if(typeof arrayName[index]==="undefined"||arrayName[index]){
     //the index is not defined or the value an empty value
}

我们就不能这样做吗

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

当你创建的空数组值不是undefined时,它们是empty

var arr = new Array(10); // (10) [empty × 10]

但是当你通过索引获取item时,receive undefined

arr[0]; // undefined

所以你不能通过===比较知道它们是未定义的还是空的

我们可以使用JSON。Stringify,转换整个数组,将空值替换为null

JSON.stringify(arr); // "[null,null,null,null,null,null,null,null,null,null]"
JSON.stringify(arr[0]); // but for single item it returns undefined

对空值的实检查:

arr[0] !== null && JSON.stringify(arr.map(item => !item)).slice(1, -1).split(',')[0] === 'null'

将item与null进行比较(不应等于) 映射数组删除false代替现有值(确保字符串结构用逗号分隔,没有多余的逗号) JSON。stringify数组 从字符串中移除括号 用逗号分割成数组 与null比较

if(arrayName.length > index && arrayName[index] !== null) {
    //arrayName[index] has a value
}
if(!arrayName[index]){
     // do stuff
}