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

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

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

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

从概念上讲,JavaScript中的数组包含数组。长度元素,从数组[0]开始,直到数组[array. array.]长度- 1]。如果i在0和array之间,则索引为i的数组元素定义为数组的一部分。长度-包括1。如果i不在这个范围内,它就不在数组中。

因此,从概念上讲,数组是线性的,从0开始,一直到最大值,没有任何机制在这个范围内存在没有条目的“间隙”。要找出一个值是否存在于给定的位置索引(其中索引为0或正整数),您只需使用

if (i >= 0 && i < array.length) {
  // it is in array
}

Now, under the hood, JavaScript engines almost certainly won't allocate array space linearly and contiguously like this, as it wouldn't make much sense in a dynamic language and it would be inefficient for certain code. They're probably hash tables or some hybrid mixture of strategies, and undefined ranges of the array probably aren't allocated their own memory. Nonetheless, JavaScript the language wants to present arrays of array.length n as having n members and they are named 0 to n - 1, and anything in this range is part of the array.

然而,您可能想要知道数组中的值是否实际上是有定义的—也就是说,它不是未定义的。也许你甚至想知道它是否有定义而不是null。可以在不设置数组值的情况下向数组添加成员:例如,如果您通过增加数组来添加数组值。属性,任何新值将是未定义的。

确定给定的值是否有意义,或者是否已定义。即非undefined或null:

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

or

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

有趣的是,由于JavaScript的比较规则,我的最后一个例子可以优化为:

if (array[index] != null) {
  // The == and != operators 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
}

if(typeof arr ==='object' && arr instanceof Array ){
   if(!arr.length){
      println 'empty'
   }else{
      printn 'not Empty'
   }

}else{
   println 'Null'
}

如果你的意思是'Null' ->它的元素为Null或等于",在这种情况下:在过滤所有'Null'元素后检查数组是否为空

if(!arr.clean().length){return 'is null'}

当然,之前的Add Clean方法:

Array.prototype.clean=function(){return this.filter(function(e){return (typeof  e !=='undefined')&&(e!= null)&&(e!='')})}

如果数组[index]为空,请尝试此操作

if (array[index] != null) 

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

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 假


你可以使用Loadsh库来更有效地做到这一点,比如:

如果你有一个名为“pets”的数组,例如:

var pets = ['dog', undefined, 'cat', null];

console.log(_.isEmpty(pets[1])); // true
console.log(_.isEmpty(pets[3])); // true
console.log(_.isEmpty(pets[4])); // false

_.map( pets, (pet, index) => { console.log(index + ': ' + _.isEmpty(pet) ) });

检查所有数组值是否为空或未定义的值:

Var pets = ['dog', undefined, 'cat', null]; 宠物console.log (_.isEmpty ([1]));/ /正确的 console.log (_.isEmpty(宠物[3]));/ /正确的 console.log (_.isEmpty(宠物[4]));/ /错误 _。地图(宠物,宠物,指数= > {console.log(指数 + ': ' + _. isEmpty (pet))}); < script src = " https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js " > < /脚本>

更多例子请访问http://underscorejs.org/


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

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

或者,我们可以用:

Object.keys(__array__).length

这取决于你对“空”的定义。

当您试图获取一个对象的属性值时,该对象没有该名称的属性,您将获得该值为undefined。

这就是稀疏数组的情况:不是所有的索引都在0和数组之间。长度为1的存在。

所以你可以检查array[index] === undefined。

但是,属性索引可能存在一个未定义的值。如果你想过滤掉这种情况,你可以使用in操作符或hasOwnProperty,如如何检查一个对象在JavaScript中是否有属性所述?

index in array;
array.hasOwnProperty(index);

如果你想要考虑一个具有未定义或空值的现有属性不存在,你可以使用松散比较数组[index] == undefined或数组[index] == null。

如果你知道数组不是稀疏的,你可以比较index和array.length。但为了安全起见,您可能希望确保index确实是数组索引,请参阅检查属性名称是否为数组索引


使用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可以继续。


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

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
}

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

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

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

对象没有长度属性。


短而通用的方法

如果你想检查任何数组是否有假值(如false, undefined, null或空字符串),你可以像这样使用every()方法:

array.every(function(element) {return !!element;}); // returns true or false

例如:

['23', null, 2, {key: 'value'}].every(function(element) {return !!element;}); // returns false

['23', '', 2, {key: 'value'}].every(function(element) {return !!element;}); // returns false

['23', true, 2, {key: 'value'}].every(function(element) {return !!element;}); // returns true

如果你需要得到一个假值的第一个索引,你可以这样做:

let falsyIndex; 

if(!['23', true, 2, null, {key: 'value'}].every(function(element, index) {falsyIndex = index; return !!element;})) {
  console.log(falsyIndex);
} // logs 3

如果你只需要检查一个给定索引的数组的假值,你可以这样做:

if (!!array[index]) {
  // array[index] is a correct value
}
else {
  // array[index] is a falsy value
}

好的,让我们先看看如果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
}

我认为这个决定适合那些喜欢声明式函数编程而不是命令式OOP或过程式编程的人。如果你的问题是“里面有价值吗?”(一个真实或虚假的值)”你可以使用。some方法来验证里面的值。

[].some(el => el || !el);

它并不完美,但它不需要应用任何包含相同逻辑的额外函数,如function isEmpty(arr){…}。 当我们这样做[]时,它听起来仍然比“它是零长度吗?”要好。长度导致0,在某些情况下是危险的。 甚至是这个[]。length > 0表示它的长度是否大于0 ?

先进的例子:

[    ].some(el => el || !el); // false
[null].some(el => el || !el); // true
[1, 3].some(el => el || !el); // true

实检测:在运算符中

这个问题的年龄大约是10年,令人惊讶的是,还没有人提到这一点-然而,有些人看到了当我们使用删除操作符(例如这里)时的问题。这也是一个有点违反直觉的解决方案,但在“对象世界”中工作的in操作符也可以用于数组(因为我们可以像在“键”上一样查看数组索引……)通过这种方式,我们可以检测并区分未定义的数组值和被delete删除的值(索引)

if(index in arrayName) {
   // do stuff 
}

let arr = [0, 1, 2, 3, null, undefined,6] delete arr[2]; // we delete element at index=2 if(2 in arr) console.log('You will not see this because idx 2 was deleted'); if(5 in arr) console.log('This is element arr[5]:', arr[5]); // Whole array and indexes bigger than arr.length: for(let i=0; i<=9; i++) { let val = (i in arr) ? arr[i] : 'empty' let bound = i<arr.length ? '' : '(out of range)' console.log(`${i} value: `, val, bound); } console.log('Look on below aray on chrome console (not in SO snippet console)'); console.log('typeof arr:', typeof arr); console.log(arr);

Chrome控制台显示了一些关于删除索引2的代码片段数组的信息-这个索引实际上根本不存在(!!)(就像从对象中删除键一样)。有趣的是,数组被视为键值对(我们甚至看到'length'键)。同样有趣的是,typeof arr是Object (!!), delete和in操作符的工作方式类似于JS对象 (同样方括号符号arr[idx]和obj[key]是类似的)-所以它看起来像数组是一些特殊的JS对象在核心。

为了得到类似的效果而不删除定义数组如下

[0, 1,, 3, null, undefined, 6] // pay attention to double comma: ",,"

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