我正在使用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数组。使用上面的代码,我仍然无法检测到不存在的索引。


当前回答

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

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

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

其他回答

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

i.e.

if(typeof arrayName[index] === 'undefined') {
    // does not exist
}
else {
    // does exist
}

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

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

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

如果你在找这样的东西。

下面是摘录

var demoArray = ['A','B','C','D']; var ArrayIndexValue = 2; 如果(demoArray.includes (ArrayIndexValue)) { 警报(“存在的价值”); //数组索引存在 其他}{ Alert(“不存在”); //数组索引不存在 }

如果你使用underscore.js,那么这些类型的null和undefined检查将被库隐藏。

所以你的代码是这样的

var currentData = new Array();

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

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

return true;

现在看起来可读性强多了。

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

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