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


当前回答

这正是in操作符的作用。像这样使用它:

if (index in currentData) 
{ 
    Ti.API.info(index + " exists: " + currentData[index]);
}

接受的答案是错误的,如果index的值未定义,它将给出假阴性:

const currentData = ['a', undefined], index = 1; if (currentData中的索引){ console.info(“存在”); } / / vs… if (typeof currentData[index] !== 'undefined') { console.info(“存在”); }其他{ Console.info('不存在');/ /不正确! }

其他回答

你可以简单地使用这个:

var tmp = ['a', 'b'];
index = 3 ;
if( tmp[index]){
    console.log(tmp[index] + '\n');
}else{
    console.log(' does not exist');
}
if(typeof arrayName[index] == undefined) {
    console.log("Doesn't exist")
}
else {
console.log("does 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
var demoArray = ['A','B','C','D'];
var ArrayIndexValue = 2;
if(ArrayIndexValue in demoArray){
   //Array index exists
}else{
   //Array Index does not Exists
}

这些天,我会利用ecmascript,像这样使用它

return myArr?.[index]