我正在使用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框架下的对象 因此,他们从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;

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

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

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 fruits =["香蕉","橙子","苹果","芒果"]; if(fruit . indexof ("Banana") == -1){ Console.log('项目不存在') }其他{ console.log(“项目存在”) }

在我看来,这种方法是最简单的。

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');
        }
 }
if(typeof arrayName[index] == undefined) {
    console.log("Doesn't exist")
}
else {
console.log("does exist")
}