如果某个数组索引中存在某个值,如何检入JavaScript?

Ank*_*kur 513 javascript arrays

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

if(arrayName[index]==""){
     // do stuff
}
Run Code Online (Sandbox Code Playgroud)

tho*_*ter 733

JavaScript中的所有数组都包含array.length元素,从array[0]最后开始array[array.length - 1].根据定义,具有索引的数组元素i被称为数组的一部分,如果i它在0和之间array.length - 1.

也就是说,JavaScript数组是线性的,从零开始并达到最大值,并且数组没有从数组中排除某些值或范围的机制.要确定给定位置索引(索引是0还是正整数)中是否存在值,您只需使用

if (index < array.length) {
  // do stuff
}
Run Code Online (Sandbox Code Playgroud)

但是,它可能的一些数组值为空,undefined,NaN,Infinity,0,或不同的值的整个主机.例如,如果通过增加array.length属性来添加数组值,则任何新值都将是undefined.

确定给定值是有意义的还是已定义的.那就是,不是 undefined,或null:

if (typeof array[index] !== 'undefined') {
Run Code Online (Sandbox Code Playgroud)

要么

if (typeof array[index] !== 'undefined' && array[index] !== null) {
Run Code Online (Sandbox Code Playgroud)

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

if (array[index] != null) {
  // The == and != operators consider null equal to only null or undefined
}  
Run Code Online (Sandbox Code Playgroud)

  • 你总是可以用`foo!= null'替换`foo!=='undefined'&& foo!== null` (9认同)
  • OP很可能知道他/她正在处理什么类型的数组,但仅仅是为了完整性:*类似数组的*对象通常也包含`length`属性,在这种情况下后两个例子更合适. (6认同)
  • 此答案不涵盖未设置数组索引的情况。`new Array(1)[0] === undefined` 但值为空。`[undefined][0] === undefined` 但值已设置;数组*有*一个值。唯一“完美”的答案是使用“in”或“hasOwnProperty()”——“idx in array”或“array.hasOwnProperty(idx)”——根据这个答案:/sf/answers/2742013431/ /3120446 (2认同)

mad*_*adi 351

我们不能这样做:

if(arrayName.length > 0){   
    //or **if(arrayName.length)**
    //this array is not empty 
}else{
   //this array is empty
}
Run Code Online (Sandbox Code Playgroud)

  • `if(arrayName.length){...`会有什么区别吗? (26认同)
  • 问题是关于如何测试数组的*特定索引*是否存在. (10认同)
  • 为什么这么多人投票?这显然不能回答这个问题. (10认同)
  • `if(arrayName.length){...`在`null`失败 (10认同)
  • 这失败了`[undefined,undefined]`这是一个长度为2的数组. (5认同)
  • @algiogia因为当你在"javascript数组空"上进行谷歌搜索时,这个问题是最重要的结果之一. (3认同)

小智 40

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

if(array && array.length){   
   // not empty 
} else {
   // empty
}
Run Code Online (Sandbox Code Playgroud)

或者,我们可以使用:

Object.keys(__array__).length
Run Code Online (Sandbox Code Playgroud)

  • «请注意,不想检查整个数组是否为空,只是某个位置的索引值为"index"» (2认同)

x2.*_*x2. 20

if(!arrayName[index]){
     // do stuff
}
Run Code Online (Sandbox Code Playgroud)

  • 如果数组值存在但是0,null,""等,这也会做. (8认同)

Rex*_*x M 8

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

  • 您可以使用 Firebug 之类的工具自行测试。在 Javascript 中,读取未定义变量的值不会引发异常——它返回未定义的值。 (2认同)

ind*_*eed 8

简短而通用的方法

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

array.every(function(element) {return !!element;}); // returns true or false
Run Code Online (Sandbox Code Playgroud)

例如:

['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
Run Code Online (Sandbox Code Playgroud)

如果你需要获得第一个falsy值索引,你可以这样做:

let falsyIndex; 

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

如果您只需要为给定索引检查数组的虚假值,您可以这样做:

if (!!array[index]) {
  // array[index] is a correct value
}
else {
  // array[index] is a falsy value
}
Run Code Online (Sandbox Code Playgroud)


Abd*_*UMI 6

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

}else{
   println 'Null'
}
Run Code Online (Sandbox Code Playgroud)

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

if(!arr.clean().length){return 'is null'}
Run Code Online (Sandbox Code Playgroud)

当然, 之前添加Clean方法:

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


l3x*_*l3x 5

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

function isEmptyEl(array, i) {
   return !(array[i]);
}
Run Code Online (Sandbox Code Playgroud)

你可以这样称呼它:

if (isEmptyEl(arrayName, indexVal)) {
   console.log('arrayName[' + indexVal + '] is empty');
}
Run Code Online (Sandbox Code Playgroud)

强制开发人员遵守isEmptyEl接口将捕获输入错误,例如未定义的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)
Run Code Online (Sandbox Code Playgroud)

未定义的indexVal的类似结果.

如果数组或索引值不存在,则会出错.

对于有效输入,只有在arrayName [indexVal]为以下任何一项时才会得到true:

  • 空值
  • 未定义
  • 为NaN
  • 空字符串
  • 0


Ori*_*iol 5

这取决于您对“空”的含义。

当您尝试在不具有该名称的属性的对象上获取属性的值时,将获得value undefined

稀疏数组就是这种情况:并非所有在0和之间的索引都array.length-1存在。

因此,您可以检查是否array[index] === undefined

但是,该属性index可以带有undefined值存在。如果要过滤掉这种情况,可以使用in运算符或hasOwnProperty,如如何检查对象在JavaScript中是否具有属性中所述。

index in array;
array.hasOwnProperty(index);
Run Code Online (Sandbox Code Playgroud)

如果要考虑不存在具有undefinednull值的现有属性,则可以使用松散比较array[index] == undefinedarray[index] == null

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

  • 这是在未设置的数组项(没有任何值)和设置为未定义值的项之间正确区分的唯一答案。这两种状态由于访问未设置的数组项返回未定义的事实而变得模糊,但是它们是不同的。 (2认同)