How to determine if object is in array

This question already has an answer here:

  • How do I check if an array includes an object in JavaScript? 40 answers

  • Use something like this:

    function containsObject(obj, list) {
        var i;
        for (i = 0; i < list.length; i++) {
            if (list[i] === obj) {
                return true;
            }
        }
    
        return false;
    }
    

    In this case, containsObject(car4, carBrands) is true. Remove the carBrands.push(car4); call and it will return false instead. If you later expand to using objects to store these other car objects instead of using arrays, you could use something like this instead:

    function containsObject(obj, list) {
        var x;
        for (x in list) {
            if (list.hasOwnProperty(x) && list[x] === obj) {
                return true;
            }
        }
    
        return false;
    }
    

    This approach will work for arrays too, but when used on arrays it will be a tad slower than the first option.


    Why don't you use the indexOf method of javascript arrays?

    Check this out: MDN indexOf Arrays

    Simply do:

    carBrands.indexOf(car1);
    

    It will return you the index (position in the array) of car1. It will return -1 if car1 was not found in the array.

    http://jsfiddle.net/Fraximus/r154cd9o

    Edit: Note that in the question, the requirements are to check for the same object referenced in the array, and NOT a new object . Even if the new object is identical in content to the object in the array, it is still a different object. As mentioned in the comments, objects are passed by reference in JS and the same object can exist multiple times in multiple structures.
    If you want to create a new object and check if the array contains objects identical to your new one, this answer won't work (Julien's fiddle below), if you want to check for that same object's existence in the array, then this answer will work. Check out the fiddles here and in the comments.


    You could use jQuery's grep method:

    $.grep(carBrands, function(obj) { return obj.name == "ford"; });
    

    But as you specify no jQuery, you could just make a derivative of the function. From the source code:

    function grepArray( elems, callback, inv ) {  
        var ret = [];  
    
        // Go through the array, only saving the items  
        // that pass the validator function  
        for ( var i = 0, length = elems.length; i < length; i++ ) {  
            if ( !inv !== !callback( elems[ i ], i ) ) {  
                ret.push( elems[ i ] );  
            }  
        }  
    
        return ret;  
    }  
    
    grepArray(carBrands, function(obj) { return obj.name == "ford"; });
    
    链接地址: http://www.djcxy.com/p/13032.html

    上一篇: jquery,检查数组中是否存在一个值

    下一篇: 如何确定对象是否在数组中