How to check if value exists in this JavaScript array?

后端 未结 5 1673
南旧
南旧 2021-01-02 00:43

I have a JavaScript array, where each new item added to the array gets the next incremental number. An example would be as follows (I hope Im writing this correctly):

<
5条回答
  •  梦谈多话
    2021-01-02 01:35

    You can use the relatively new Array.prototype.some() to find whether an item exists (a shim is provided in the documentation):

    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

提交回复
热议问题