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

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

当前回答

我建议创建一个这样的函数:

function isEmptyEl(array, i) {
   return !(array[i]);
}

你可以这样称呼它:

if (isEmptyEl(arrayName, indexVal)) {
   console.log('arrayName[' + indexVal + '] is empty');
}

强制开发人员使用isemptyl接口将捕获输入错误,例如未定义的arrayName或indexVal变量。

(在使用Javascript编程时,防御性编程通常是一个很好的实践。)

如果没有定义arrayName,就会抛出这样的错误:

Uncaught ReferenceError: arrayName is not defined
    at <anonymous>:2:15
    at Object.InjectedScript._evaluateOn (<anonymous>:895:140)
    at Object.InjectedScript._evaluateAndWrap (<anonymous>:828:34)
    at Object.InjectedScript.evaluate (<anonymous>:694:21)

未定义的indexVal也有类似的结果。

如果数组或索引值不存在,就会得到一个错误。

对于有效的输入,如果arrayName[indexVal]是以下任意一个,你只会得到一个true:

零 未定义的 南 空字符串 0 假

其他回答

我们就不能这样做吗

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

好的,让我们先看看如果JavaScript中不存在数组值会发生什么,所以如果我们有一个如下所示的数组:

const arr = [1, 2, 3, 4, 5];

现在我们检查6是否在下标5处:

arr[5];

我们得到 未定义……

这基本上给了我们答案,检查是否未定义的最好方法,像这样:

if("undefined" === typeof arrayName[index]) {
  //array value is not there...
}

在这种情况下最好不要这样做:

if(!arrayName[index]) {
  //Don't check like this..
}

因为假设我们有这样一个数组:

const arr = [0, 1, 2];

我们这样做:

if(!arr[0]) {
  //This get passed, because in JavaScript 0 is falsy
}

正如你所看到的,即使0在那里,它也不会被识别,还有一些其他的事情可以做同样的事情,让你的应用程序有bug,所以要小心,我把它们都列了下来:

Undefined:如果该值没有定义并且是未定义的 null:如果它是空的,例如如果一个DOM元素不存在… 空字符串:" 0:数字0 南:不是数字 假

我想指出一些似乎已经错过的东西:即有可能在数组的中间有一个“空”数组位置。考虑以下几点:

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

自然的检查方法是查看数组成员是否未定义,我不确定是否存在其他方法

if (arr[index] === undefined) {
  // member does not exist
}
if(arrayName.length > index && arrayName[index] !== null) {
    //arrayName[index] has a value
}
if(!arrayName[index]){
     // do stuff
}