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


当前回答

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

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 nameList = new Array('item1','item2','item3','item4');

// Using for loop to loop through each item to check if item exist.

for (var i = 0; i < nameList.length; i++) {
if (nameList[i] === 'item1') 
{   
   alert('Value exist');
}else{
   alert('Value doesn\'t exist');
}

也许另一种方法是。

nameList.forEach(function(ItemList)
 {
   if(ItemList.name == 'item1')
        {
          alert('Item Exist');
        }
 }

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

return myArr?.[index]

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

如果我说错了,请谁纠正我,但我相信下面是真的:

数组实际上只是JS框架下的对象 因此,他们从Object“继承”了原型方法hasOwnProperty 在我的测试中,hasOwnProperty可以检查数组下标是否存在任何东西。

所以,只要上述条件成立,你就可以简单地:

const arrayHasIndex = (array, index) => array. isarray (array) && array. hasownproperty (index);

用法:

arrayHasIndex((1、2、3、4),4);输出:假

arrayHasIndex((1、2、3、4),2);输出:真

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

所以你的代码是这样的

var currentData = new Array();

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

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

return true;

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