如果某个值存在于某个数组索引处,我如何检查 JavaScript?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2672380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:24:05  来源:igfitidea点击:

How do I check in JavaScript if a value exists at a certain array index?

javascriptarrays

提问by Ankur

Will this work for testing whether a value at position "index" exists or not, or is there a better way:

这是否适用于测试位置“index”处的值是否存在,或者是否有更好的方法:

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

回答by thomasrutter

Conceptually, arrays in JavaScript contain array.lengthelements, starting with array[0]up until array[array.length - 1]. An array element with index iis defined to be part of the array if iis between 0and array.length - 1inclusive. If i is not in this range it's not in the array.

从概念上讲,JavaScript 中的数组包含array.length元素,从array[0]直到array[array.length - 1]. 具有索引的数组元素i被定义为所述阵列的一部分,如果i是间0array.length - 1包容。如果 i 不在此范围内,则它不在数组中。

So by concept, arrays are linear, starting with zero and going to a maximum, without any mechanism for having "gaps" inside that range where no entries exist. To find out if a value exists at a given position index (where index is 0 or a positive integer), you literally just use

因此,从概念上讲,数组是线性的,从零开始到最大值,没有任何机制可以在不存在条目的范围内产生“间隙”。要找出给定位置索引处是否存在值(其中索引为 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.lengthnas having nmembers and they are named 0to n - 1, and anything in this range is part of the array.

现在,在幕后,JavaScript 引擎几乎肯定不会像这样线性和连续地分配数组空间,因为它在动态语言中没有多大意义,并且对于某些代码来说效率低下。它们可能是哈希表或一些混合策略,并且未定义的数组范围可能没有分配自己的内存。尽管如此,JavaScript 语言希望将array.lengthn数组呈现为具有n 个成员,并且它们被命名为0n - 1,并且此范围内的任何内容都是数组的一部分。

What you probably want, however, is to know if a value in an array is actually something defined- that is, it's not undefined. Maybe you even want to know if it's defined and not null. It's possible to add members to an array without ever setting their value: for example, if you add array values by increasing the array.lengthproperty, any new values will be undefined.

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

To determine if a given value is something meaningful, or has been defined. That is, notundefined, or null:

确定给定的值是否有意义,或已被定义。也就是说,不是undefined,或者null

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

or

或者

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

Interestingly, because of JavaScript's comparison rules, my last example can be optimised down to this:

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

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

回答by madi

Can't we just do this:

我们不能这样做:

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

回答by Joni

Using only .lengthis not safe and will cause an error in some browsers. Here is a better solution:

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

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

or, we can use:

或者,我们可以使用:

Object.keys(__array__).length

回答by x2.

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

回答by indreed

Short and universal approach

简短而通用的方法

If you want to check any array if it has falsy values (like false, undefined, null or empty strings) you can just use every()method like this:

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

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

For example:

例如:

['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

If you need to get a first index of falsy value, you can do it like this:

如果您需要获取虚假值的第一个索引,您可以这样做:

let falsyIndex; 

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

If you just need to check a falsy value of an array for a given index you can just do it like this:

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

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

回答by Rex M

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

回答by Abdennour TOUMI

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

}else{
   println 'Null'
}

If you mean by 'Null' -> Its elements are null or equals to '' , in this case : Check if the array is empty after filtering all 'null' elements

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

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

Of course ,Add Cleanmethod before :

当然, 之前添加Clean方法:

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

回答by l3x

I would recommend creating a function like this:

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

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

You could call it like this:

你可以这样称呼它:

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

Forcing the developer to adhere to the isEmptyEl interface will catch input errors such as an undefined arrayName or indexVal variables.

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

(It's generally good practice to program defensively when programming in Javascript.)

(在使用 Javascript 编程时进行防御性编程通常是一种很好的做法。)

You would get an error thrown like this if arrayName was not defined:

如果 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)

Similar results for an undefined indexVal.

未定义的 indexVal 的类似结果。

You get an error if the array or index values do not exist.

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

For valid input, you'll only get a true if arrayName[indexVal] is any of the following:

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

  • null
  • undefined
  • NaN
  • empty string
  • 0
  • false
  • 空值
  • 不明确的
  • NaN
  • 空字符串
  • 0
  • 错误的

回答by Oriol

It depends on what you mean with "empty".

这取决于你对“空”的意思。

When you attempt to get the value of a property on an object which has no property with that name, you will get the value undefined.

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

That's what happens with sparse arrays: not all indices between 0and array.length-1exist.

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

So you could check if array[index] === undefined.

所以你可以检查是否array[index] === undefined.

However, the property indexcould exist with an undefinedvalue. If you want to filter out this case, you can use the inoperator or hasOwnProperty, as described in How do I check if an object has a property in JavaScript?

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

index in array;
array.hasOwnProperty(index);

If you want consider an existing property with an undefinedor nullvalue to not exist, you can use the loose comparison array[index] == undefinedor array[index] == null.

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

If you know the array is not sparse, you could compare indexwith array.length. But to be safe, you may want to ensure that indexreally is an array index, see Check if property name is array index

如果您知道数组不是稀疏的,则可以indexarray.length. 但为了安全起见,您可能要确保index确实是数组索引,请参阅检查属性名称是否为数组索引

回答by Alireza

OK,let's first see what would happens if an array value not exist in JavaScript, so if we have an array like below:

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

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

and now we check if 6is there at index 5or not:

现在我们检查6是否在索引5 处

arr[5];

and we get undefined...

我们得到 undefined...

So that's basically give us the answer, the best wayto check if undefined, so something like this:

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

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

It's better NOTdoing this in this case:

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

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

Because imagine we have this array:

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

const arr = [0, 1, 2];

and we do:

我们这样做:

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

So as you see, even 0is there, it doesn't get recognised, there are few other things which can do the same and make you application buggy, so be careful, I list them all down:

因此,如您所见,即使是0,也不会被识别,很少有其他事情可以做同样的事情并使您的应用程序出错,所以要小心,我将它们全部列出:

  1. undefined: if the value is not defined and it's undefined
  2. null: if it's null, for example if a DOM element not exists...
  3. empty string: ''
  4. 0: number zero
  5. NaN: not a number
  6. false
  1. undefined:如果该值未定义并且它是undefined
  2. null: 如果它是 null,例如如果 DOM 元素不存在...
  3. 空字符串''
  4. 0: 数字零
  5. NaN: 不是数字
  6. 错误的