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


当前回答

考虑数组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')

其他回答

(typeof files[1] === undefined)?
            this.props.upload({file: files}):
            this.props.postMultipleUpload({file: files widgetIndex: 0, id})

使用typeof检查数组中的第二项是否为undefined,并检查是否为undefined

简单的方法来检查项目是否存在

Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--)
       if (this[i] == obj)
       return true;
    return false;
}

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

myArray.contains("Apple")
if(typeof arrayName[index] == undefined) {
    console.log("Doesn't exist")
}
else {
console.log("does exist")
}
var myArray = ["Banana", "Orange", "Apple", "Mango"];

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

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

i.e.

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