Determine whether an array contains a value

This question already has an answer here:

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

  • var contains = function(needle) {
        // Per spec, the way to identify NaN is that it is not equal to itself
        var findNaN = needle !== needle;
        var indexOf;
    
        if(!findNaN && typeof Array.prototype.indexOf === 'function') {
            indexOf = Array.prototype.indexOf;
        } else {
            indexOf = function(needle) {
                var i = -1, index = -1;
    
                for(i = 0; i < this.length; i++) {
                    var item = this[i];
    
                    if((findNaN && item !== item) || item === needle) {
                        index = i;
                        break;
                    }
                }
    
                return index;
            };
        }
    
        return indexOf.call(this, needle) > -1;
    };
    

    You can use it like this:

    var myArray = [0,1,2],
        needle = 1,
        index = contains.call(myArray, needle); // true
    

    CodePen validation/usage


    jQuery has a utility function for this:

    $.inArray(value, array)
    

    Returns index of value in array . Returns -1 if array does not contain value .

    See also How do I check if an array includes an object in JavaScript?


    This is generally what the indexOf() method is for. You would say:

    return arrValues.indexOf('Sam') > -1
    
    链接地址: http://www.djcxy.com/p/9570.html

    上一篇: jQuery复选框选中状态更改事件

    下一篇: 确定一个数组是否包含一个值