如何检查此JavaScript数组中是否存在值?

时间:2011-10-12 12:42:39

标签: javascript arrays

我有一个JavaScript数组,其中添加到数组的每个新项都获得下一个增量数。一个例子如下(我希望我正确地写这个):

ArrayofPeople[0] = [{"id": "529", "name": "Bob"}];
ArrayofPeople[1] = [{"id": "820", "name": "Dave"}];
ArrayofPeople[2] = [{"id": "235", "name": "John"}];

数组名为ArrayofPeople,为每个人存储多个数据点。

我需要知道数组中是否存在id为820的元素。怎么会这样做?

5 个答案:

答案 0 :(得分:10)

这样的事情:

function in_array(array, id) {
    for(var i=0;i<array.length;i++) {
        return (array[i][0].id === id)
    }
    return false;
}

var result = in_array(ArrayofPeople, 235);

答案 1 :(得分:6)

你应该迭代数组并手动检查你是否有匹配的id:

function getPersonById(id){
    for(var i=0,l=ArrayofPeople.length;i<l;i++)
       if(ArrayofPeople[0][i].id == id)
           return ArrayofPeople[i];
    return null;
}

当然,这是非常低效的。我建议你将对象存储到一个由人的id索引的关联数组(也就是一个对象)中。然后,对具有特定id的人的访问是立即的,因为对象不是散列表:

ArrayofPeople = {};
ArrayofPeople[529] = {"id": "529", "name": "Bob"};
ArrayofPeople[820] = {"id": "820", "name": "Dave"};
ArrayofPeople[235] = {"id": "235", "name": "John"};

 function getPersonById(id){
   return id in ArrayofPeople
       ? ArrayofPeople[id]
       : null;
}

答案 2 :(得分:4)

您可以使用相对较新的Array.prototype.some()来查找项目是否存在(文档中提供了填充程序):

var ArrayofPeople = [];
ArrayofPeople[0] = [{"id": "529", "name": "Bob"}];
ArrayofPeople[1] = [{"id": "820", "name": "Dave"}];
ArrayofPeople[2] = [{"id": "235", "name": "John"}];

function in_array(array, id) 
{
    return array.some(function(item) {
        return item[0].id === id;
    });
}

console.log(in_array(ArrayofPeople, '820')); // true

答案 3 :(得分:1)

ArrayofPeople = new Array();
ArrayofPeople[0] = [{"id": "529", "name": "Bob"}];
ArrayofPeople[1] = [{"id": "820", "name": "Dave"}];
ArrayofPeople[2] = [{"id": "235", "name": "John"}];

var str = '820';
var is_found = 'not found';
for(item in ArrayofPeople){
    target = ArrayofPeople[item][0];
    if(target['id'] === str)
        is_found = 'found';
}
alert(is_found);

答案 4 :(得分:0)

function IsIdInArray(array, id) {
  for (var i = 0; i < array.length; i++) {
    if (array[i].id === id)
      return true;
  }
  return false;
}

var result = IsIdInArray(ArrayofPeople, 820);