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


当前回答

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

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

其他回答

这正是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('不存在');/ /不正确! }

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

如果你使用underscore.js,那么这些类型的null和undefined检查将被库隐藏。

所以你的代码是这样的

var currentData = new Array();

if (_.isEmpty(currentData)) return false;

Ti.API.info("is exists  " + currentData[index]);

return true;

现在看起来可读性强多了。

var demoArray = ['A','B','C','D'];
var ArrayIndexValue = 2;
if(ArrayIndexValue in demoArray){
   //Array index exists
}else{
   //Array Index does not Exists
}