我正在使用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 demoArray = ['A','B','C','D'];
var ArrayIndexValue = 2;
if(ArrayIndexValue in demoArray){
   //Array index exists
}else{
   //Array Index does not Exists
}

其他回答

如果你使用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');
        }
 }

一行验证。最简单的方法。

return !!currentData[index];

输出

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

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

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

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

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

这也很好,使用===对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(“里面有樱桃!”) }