如何检查javascript中是否存在数组索引?

2022-08-30 00:23:31

我正在使用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


答案 1

typeof arrayName[index] === 'undefined'

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

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

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