我正在使用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; 如果(demoArray.includes (ArrayIndexValue)) { 警报(“存在的价值”); //数组索引存在 其他}{ Alert(“不存在”); //数组索引不存在 }

其他回答

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

var fruits =["香蕉","橙子","苹果","芒果"]; if(fruit . indexof ("Banana") == -1){ Console.log('项目不存在') }其他{ console.log(“项目存在”) }

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

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

let a = [];
a[1] = 'foo';
console.log(!!a[0])   // false
console.log(!!a[1])   // true

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