Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/386.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何检查此JavaScript数组中是否存在值?_Javascript_Arrays - Fatal编程技术网

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

如何检查此JavaScript数组中是否存在值?,javascript,arrays,Javascript,Arrays,我有一个JavaScript数组,其中添加到数组中的每个新项都会获得下一个增量数字。下面是一个例子(我希望我写的是正确的): 该数组名为ArrayofPeople,为每个人存储多个数据点 我需要知道数组中是否存在id为820的元素。如何实现这一点?您应该迭代数组并手动检查是否有匹配的id: function getPersonById(id){ for(var i=0,l=ArrayofPeople.length;i<l;i++) if(ArrayofPeople[i

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

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


我需要知道数组中是否存在id为820的元素。如何实现这一点?

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

function getPersonById(id){
    for(var i=0,l=ArrayofPeople.length;i<l;i++)
       if(ArrayofPeople[i][0].id == id)
           return ArrayofPeople[i];
    return null;
}
大概是这样的:

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);
_数组中的函数(数组,id){
对于(var i=0;i,您可以使用相对较新的来查找项目是否存在(文档中提供了一个垫片):

var ArrayofPeople=[];
ArrayofPeople[0]=[{“id”:“529”,“名称”:“Bob”}];
ArrayofPeople[1]=[{“id”:“820”,“名称”:“Dave”}];
ArrayofPeople[2]=[{“id”:“235”,“name”:“John”}];
_数组中的函数(数组,id)
{
返回数组.some(函数(项){
返回项[0]。id==id;
});
}
log(在数组中(ArrayofPeople,'820');//true
函数IsIdInArray(数组,id){
对于(var i=0;i
如果为false,这似乎对我有效,但如果为true,它将完全停止工作。我在该检查中做错了什么?:
如果(在数组中(ArrayofPeople,235)==true){alert(“事件在数组中”);}或者{alert(“不在数组中”)}
因为您将id存储为字符串,应该在数组中(ArrayofPeople,235'))或者您需要从ArrayOW中的id属性中删除“”,将近4年了,没有人提到此代码不起作用!只有当第一个元素的id等于id参数时,代码才会检查!将内部循环体更改为
if(array[i][0]。id==id)返回true;
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;
}
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);
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);