我正在使用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;
}

我传递一个索引到currentData数组。使用上面的代码,我仍然无法检测到不存在的索引。


当前回答

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

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

其他回答

在我看来,这种方法是最简单的。

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');
}

也许另一种方法是。

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

考虑数组a:

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

如果你想检查'name1'是否存在于a中,只需用in测试它:

if('name1' in a){
console.log('name1 exists in a')
}else
console.log('name1 is not in a')
var myArray = ["Banana", "Orange", "Apple", "Mango"];

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

如果数组的元素也是简单对象或数组,你可以使用一些函数:

// 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;
    }
});

如果我说错了,请谁纠正我,但我相信下面是真的:

数组实际上只是JS框架下的对象 因此,他们从Object“继承”了原型方法hasOwnProperty 在我的测试中,hasOwnProperty可以检查数组下标是否存在任何东西。

所以,只要上述条件成立,你就可以简单地:

const arrayHasIndex = (array, index) => array. isarray (array) && array. hasownproperty (index);

用法:

arrayHasIndex((1、2、3、4),4);输出:假

arrayHasIndex((1、2、3、4),2);输出:真