简体   繁体   English

如何检查javascript中是否存在数组索引?

[英]How to check if an array index exists or not in javascript?

I am working with Titanium, my code looks like this:我正在使用 Titanium,我的代码如下所示:

var currentData = new Array();
if(currentData[index]!==""||currentData[index]!==null||currentData[index]!=='null')
{
    Ti.API.info("is exists  " + currentData[index]);
    return true;
}
else
{   
    return false;
}

I am passing an index to the currentData array.我正在将索引传递给currentData数组。 I still can't detect a non-existing index using the above code.我仍然无法使用上面的代码检测到不存在的索引。

Use typeof arrayName[index] === 'undefined'使用typeof arrayName[index] === 'undefined'

ie IE

if(typeof arrayName[index] === 'undefined') {
    // does not exist
}
else {
    // does exist
}
var myArray = ["Banana", "Orange", "Apple", "Mango"];

if (myArray.indexOf(searchTerm) === -1) {
  console.log("element doesn't exist");
}
else {
  console.log("element found");
}

Someone please correct me if i'm wrong, but AFAIK the following is true:如果我错了,请有人纠正我,但AFAIK以下是正确的:

  1. Arrays are really just Objects under the hood of JS数组实际上只是 JS 引擎盖下的对象
  2. Thus, they have the prototype method hasOwnProperty "inherited" from Object因此,他们有原型方法hasOwnPropertyObject “继承”
  3. in my testing, hasOwnProperty can check if anything exists at an array index.在我的测试中, hasOwnProperty可以检查数组索引处是否存在任何内容。

So, as long as the above is true, you can simply:因此,只要上述情况属实,您可以简单地:

const arrayHasIndex = (array, index) => Array.isArray(array) && array.hasOwnProperty(index);

usage:用法:

arrayHasIndex([1,2,3,4],4); outputs: false输出: false

arrayHasIndex([1,2,3,4],2); outputs: true输出: true

This is exactly what the in operator is for.这正是in运算符的用途。 Use it like this:像这样使用它:

if (index in currentData) 
{ 
    Ti.API.info(index + " exists: " + currentData[index]);
}

The accepted answer is wrong, it will give a false negative if the value at index is undefined :接受的答案是错误的,如果index处的值undefined ,它将给出错误否定:

 const currentData = ['a', undefined], index = 1; if (index in currentData) { console.info('exists'); } // ...vs... if (typeof currentData[index] !== 'undefined') { console.info('exists'); } else { console.info('does not exist'); // incorrect! }

这些天我会利用 ecmascript 并像那样使用它

return myArr?.[index]

I had to wrap techfoobar's answer in a try .. catch block, like so:我不得不将 techfoobar 的答案包装在try .. catch块中,如下所示:

try {
  if(typeof arrayName[index] == 'undefined') {
    // does not exist
  }
  else {
  // does exist
  }
} 
catch (error){ /* ignore */ }

...that's how it worked in chrome, anyway (otherwise, the code stopped with an error). ...无论如何,这就是它在 chrome 中的工作方式(否则,代码会因错误而停止)。

If elements of array are also simple objects or arrays, you can use some function:如果数组的元素也是简单的对象或数组,你可以使用一些函数:

// search object
var element = { item:'book', title:'javasrcipt'};

[{ item:'handbook', title:'c++'}, { item:'book', title:'javasrcipt'}].some(function(el){
    if( el.item === element.item && el.title === element.title ){
        return true; 
     } 
});

[['handbook', 'c++'], ['book', 'javasrcipt']].some(function(el){
    if(el[0] == element.item && el[1] == element.title){
        return true;
    }
});

Consider the array a:考虑数组 a:

var a ={'name1':1, 'name2':2}

If you want to check if 'name1' exists in a, simply test it with in :如果你想检查 'name1' 是否存在于 a 中,只需用in测试它:

if('name1' in a){
console.log('name1 exists in a')
}else
console.log('name1 is not in a')
var demoArray = ['A','B','C','D'];
var ArrayIndexValue = 2;
if(ArrayIndexValue in demoArray){
   //Array index exists
}else{
   //Array Index does not Exists
}

If you are looking for some thing like this.如果你正在寻找这样的东西。

Here is the following snippetr这是以下代码段

 var demoArray = ['A','B','C','D']; var ArrayIndexValue = 2; if(demoArray.includes(ArrayIndexValue)){ alert("value exists"); //Array index exists }else{ alert("does not exist"); //Array Index does not Exists }

 var fruits = ["Banana", "Orange", "Apple", "Mango"]; if(fruits.indexOf("Banana") == -1){ console.log('item not exist') } else { console.log('item exist') }

If you use underscore.js then these type of null and undefined check are hidden by the library.如果您使用underscore.js,那么库会隐藏这些类型的 null 和 undefined 检查。

So your code will look like this -所以你的代码看起来像这样 -

var currentData = new Array();

if (_.isEmpty(currentData)) return false;

Ti.API.info("is exists  " + currentData[index]);

return true;

It looks much more readable now.它现在看起来更具可读性。

This way is easiest one in my opinion.这种方式在我看来是最简单的。

var nameList = new Array('item1','item2','item3','item4');

// Using for loop to loop through each item to check if item exist.

for (var i = 0; i < nameList.length; i++) {
if (nameList[i] === 'item1') 
{   
   alert('Value exist');
}else{
   alert('Value doesn\'t exist');
}

And Maybe Another way to do it is.也许另一种方法是。

nameList.forEach(function(ItemList)
 {
   if(ItemList.name == 'item1')
        {
          alert('Item Exist');
        }
 }

Simple way to check item exist or not检查项目是否存在的简单方法

Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--)
       if (this[i] == obj)
       return true;
    return false;
}

var myArray= ["Banana", "Orange", "Apple", "Mango"];

myArray.contains("Apple")

When trying to find out if an array index exists in JS, the easiest and shortest way to do it is through double negation.当试图找出 JS 中是否存在数组索引时,最简单、最短的方法是通过双重否定。

let a = [];
a[1] = 'foo';
console.log(!!a[0])   // false
console.log(!!a[1])   // true
const arr = []

typeof arr[0] // "undefined"

arr[0] // undefined

If boolean expression如果布尔表达式

typeof arr[0] !== typeof undefined

is true then 0 is contained in arr为真则 0 包含在 arr 中

One line validation.一行验证。 The simplest way.最简单的方法。

return !!currentData[index];

Outputs产出

var testArray = ["a","b","c"]

testArray[5]; //output => undefined
testArray[1]; //output => "b"

!!testArray[5]; //output => false
!!testArray[1]; //output => true

you can simply use this:你可以简单地使用这个:

var tmp = ['a', 'b'];
index = 3 ;
if( tmp[index]){
    console.log(tmp[index] + '\n');
}else{
    console.log(' does not exist');
}
(typeof files[1] === undefined)?
            this.props.upload({file: files}):
            this.props.postMultipleUpload({file: files widgetIndex: 0, id})

Check if the second item in the array is undefined using the typeof and checking for undefined使用typeof检查数组中的第二项是否未定义并检查undefined

if(typeof arrayName[index] == undefined) {
    console.log("Doesn't exist")
}
else {
console.log("does exist")
}

This also works fine, testing by type against undefined .这也可以正常工作,按类型针对undefined进行测试。

if (currentData[index] === undefined){return}

Test:测试:

 const fruits = ["Banana", "Orange", "Apple", "Mango"]; if (fruits["Raspberry"] === undefined){ console.log("No Raspberry entry in fruits!") }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM