繁体   English   中英

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

[英]How to check if an array index exists or not in javascript?

我正在使用 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 arrayName[index] === 'undefined'

IE

if(typeof arrayName[index] === 'undefined') {
    // does not exist
}
else {
    // does exist
}
var myArray = ["Banana", "Orange", "Apple", "Mango"];

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

如果我错了,请有人纠正我,但AFAIK以下是正确的:

  1. 数组实际上只是 JS 引擎盖下的对象
  2. 因此,他们有原型方法hasOwnPropertyObject “继承”
  3. 在我的测试中, hasOwnProperty可以检查数组索引处是否存在任何内容。

因此,只要上述情况属实,您可以简单地:

const arrayHasIndex = (array, index) => Array.isArray(array) && array.hasOwnProperty(index);

用法:

arrayHasIndex([1,2,3,4],4); 输出: false

arrayHasIndex([1,2,3,4],2); 输出: true

这正是in运算符的用途。 像这样使用它:

if (index in currentData) 
{ 
    Ti.API.info(index + " exists: " + currentData[index]);
}

接受的答案是错误的,如果index处的值undefined ,它将给出错误否定:

 const currentData = ['a', undefined], index = 1; if (index in currentData) { console.info('exists'); } // ...vs... if (typeof currentData[index] !== 'undefined') { console.info('exists'); } else { console.info('does not exist'); // incorrect! }

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

return myArr?.[index]

我不得不将 techfoobar 的答案包装在try .. catch块中,如下所示:

try {
  if(typeof arrayName[index] == 'undefined') {
    // does not exist
  }
  else {
  // does exist
  }
} 
catch (error){ /* ignore */ }

...无论如何,这就是它在 chrome 中的工作方式(否则,代码会因错误而停止)。

如果数组的元素也是简单的对象或数组,你可以使用一些函数:

// search object
var element = { item:'book', title:'javasrcipt'};

[{ item:'handbook', title:'c++'}, { item:'book', title:'javasrcipt'}].some(function(el){
    if( el.item === element.item && el.title === element.title ){
        return true; 
     } 
});

[['handbook', 'c++'], ['book', 'javasrcipt']].some(function(el){
    if(el[0] == element.item && el[1] == element.title){
        return true;
    }
});

考虑数组 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')
var demoArray = ['A','B','C','D'];
var ArrayIndexValue = 2;
if(ArrayIndexValue in demoArray){
   //Array index exists
}else{
   //Array Index does not Exists
}

如果你正在寻找这样的东西。

这是以下代码段

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

 var fruits = ["Banana", "Orange", "Apple", "Mango"]; if(fruits.indexOf("Banana") == -1){ console.log('item not exist') } else { console.log('item exist') }

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

所以你的代码看起来像这样 -

var currentData = new Array();

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

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

return 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');
        }
 }

检查项目是否存在的简单方法

Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--)
       if (this[i] == obj)
       return true;
    return false;
}

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

myArray.contains("Apple")

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

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

typeof arr[0] // "undefined"

arr[0] // undefined

如果布尔表达式

typeof arr[0] !== typeof undefined

为真则 0 包含在 arr 中

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

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 tmp = ['a', 'b'];
index = 3 ;
if( tmp[index]){
    console.log(tmp[index] + '\n');
}else{
    console.log(' does not exist');
}
(typeof files[1] === undefined)?
            this.props.upload({file: files}):
            this.props.postMultipleUpload({file: files widgetIndex: 0, id})

使用typeof检查数组中的第二项是否未定义并检查undefined

if(typeof arrayName[index] == undefined) {
    console.log("Doesn't exist")
}
else {
console.log("does exist")
}

这也可以正常工作,按类型针对undefined进行测试。

if (currentData[index] === undefined){return}

测试:

 const fruits = ["Banana", "Orange", "Apple", "Mango"]; if (fruits["Raspberry"] === undefined){ console.log("No Raspberry entry in fruits!") }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM