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


当前回答

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

其他回答

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

return !!currentData[index];

输出

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

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

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

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

let a = [];
a[1] = 'foo';
console.log(!!a[0])   // false
console.log(!!a[1])   // 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(“里面有樱桃!”) }

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