我正在使用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 tmp = ['a', 'b'];
index = 3 ;
if( tmp[index]){
    console.log(tmp[index] + '\n');
}else{
    console.log(' does not exist');
}

其他回答

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

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

当试图找出JS中是否存在数组索引时,最简单和最短的方法是通过双重否定。

let a = [];
a[1] = 'foo';
console.log(!!a[0])   // false
console.log(!!a[1])   // true
if(typeof arrayName[index] == undefined) {
    console.log("Doesn't exist")
}
else {
console.log("does exist")
}

这也很好,使用===对undefined进行类型测试。

if (array[index] === undefined){ return } // True

测试:

const fruits =["香蕉","橘子","苹果","芒果"]; if (fruit ["Cherry"] === undefined){ console.log("There 't any cherry in the fruits basket:(") }

或类似的:

const fruits =["香蕉","橘子","苹果","芒果"]; 如果(!水果(“樱桃”)){ console.log("There 't any cherry in the fruits basket:(") } //没有错误: 如果(水果(“樱桃”)){ console.log(“里面有樱桃!”) }

我必须把techfoobar的答案包装在一个try. catch块中,就像这样:

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

...无论如何,这就是它在chrome中的工作方式(否则,代码会因错误而停止)。