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

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

当前回答

当你创建的空数组值不是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比较

其他回答

当你创建的空数组值不是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比较

我在使用laravel数据表时遇到了这个问题。我在活动日志中存储了一个名为properties的JSON值,并希望根据该值是否为空来显示一个按钮。

好吧,数据表是解释这作为一个数组,如果它是空的,和一个对象,如果它不是,因此,下面的解决方案为我工作:

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

对象没有长度属性。

使用Lodash,你可以做到:

if(_.has(req,'documents')){
      if (req.documents.length)
      _.forEach(req.documents, function(document){
        records.push(document);
      });
} else {
}

if(_.has(req,'documents'))是检查我们的请求对象是否有一个名为documents的属性,如果它有prop,下一个if(req.documents.length)是验证它是否不是一个空数组,这样其他的东西,如forEach可以继续。

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

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[index]){
     // do stuff
}