如何在JavaScript中检查特定数组索引处是否存在值?

541

这个代码可以用来测试位置为index的值是否存在,或者有更好的方法吗:

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

6
请注意,不想检查整个数组是否为空,只是想检查具有索引值“index”的特定位置。 - Ankur
标题可以改进为“如何在JavaScript中检查特定数组索引处是否存在值”。 - demisx
19个回答

2

真正的检测方法: in运算符

这个问题已经存在了大约10年,令人惊讶的是,到目前为止没有人提到过 - 然而一些人在使用delete运算符时(例如这里),会发现这个问题。这也是一个有点反直觉的解决方案,但是在“对象世界”中工作的in运算符也可以与数组一起使用(因为我们可以像处理“键”一样来处理数组索引)。通过这种方式,我们可以检测和区分undefined数组值和被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 (!!!),deletein运算符的工作方式类似于JS对象(方括号表示法arr[idx]obj[key]也很相似) - 这样看来数组是JS核心中的一些特殊JS对象。

enter image description here

要获得类似的效果而不使用delete,请按以下方式定义数组:

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

1

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

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

现在我们检查6是否在索引5处:
arr[5];

我们得到了undefined...

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

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存在,它也不会被识别,还有其他一些东西也会导致应用程序出错,因此要小心,我把它们都列出来了:
  1. 未定义:如果值未定义并且是undefined
  2. null:如果为null,例如如果DOM元素不存在...
  3. 空字符串''
  4. 0:数字零
  5. NaN:不是数字
  6. false

0

检查变量是否未定义或已被删除:

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

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

要检查它是否从未被定义、已被删除或者是 null 或逻辑空值(NaN、空字符串、false):

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

0
我在使用Laravel Datatables时遇到了这个问题。我在活动日志中存储了一个名为properties的JSON值,并希望根据该值是否为空来显示一个按钮。
然而,如果它是空的,Datatables会将其解释为一个数组,如果不是,则解释为一个对象,因此,以下解决方案适用于我:
render: function (data, type, full) {
    if (full.properties.length !== 0) {
        // do stuff
    }
}

对象没有长度属性。


0

当你创建空数组时,值不是undefined,而是空的

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

但是当您通过索引获取项时,会收到未定义的值

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'
  1. 将项目与 null 进行比较(应该不相等)
  2. 映射数组,删除 false 而不是现有值(确保字符串结构为逗号分隔,没有冗余逗号)
  3. JSON.stringify 数组
  4. 从字符串中删除括号
  5. 通过逗号拆分成数组
  6. null 进行比较

0

我认为这个决定适合那些喜欢声明式函数式编程而非命令式面向对象编程或过程式编程的人。如果你的问题是 "里面有值吗?(真值或假值)", 你可以使用 .some 方法来验证里面的值。

[].some(el => el || !el);
  • 它并不完美,但不需要应用任何包含相同逻辑的额外函数,比如function isEmpty(arr) { ... }
  • 当我们执行[].length得到0时,这仍然比"它的长度是零吗?"听起来更好,而在某些情况下,0是危险的。
  • 甚至这个[].length > 0"它的长度是否大于零?"

高级示例:

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

0

如果数组[index]为空,请尝试这个

if (array[index] != null) 

0
使用 Lodash,你可以做到以下操作:
if(_.has(req,'documents')){
      if (req.documents.length)
      _.forEach(req.documents, function(document){
        records.push(document);
      });
} else {
}

if(_.has(req,'documents')) 是为了检查我们的请求对象是否有一个名为 documents 的属性,如果有该属性,则下一个 if (req.documents.length) 用于验证它是否不是空数组,以便其他像 forEach 这样的操作可以继续进行。


-1

您可以使用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) ) });

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

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) ) });
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

http://underscorejs.org/中查看更多示例


fn(){}是语法错误,而且不清楚它如何帮助检查一个数组项是否存在于特定的索引位置。 - Oriol

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接