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


当前回答

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

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

其他回答

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

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

i.e.

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

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

return myArr?.[index]

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

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

return !!currentData[index];

输出

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

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

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