Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

javascript - 确定数组是否包含值[重复](Determine whether an array contains a value [duplicate])

I need to determine if a value exists in an array.

(我需要确定数组中是否存在值。)

I am using the following function:

(我正在使用以下功能:)

Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i] == obj) {
            return true;
        }
    }
    return false;
}

The above function always returns false.

(上面的函数总是返回false。)

The array values and the function call is as below:

(数组值和函数调用如下:)

arrValues = ["Sam","Great", "Sample", "High"]
alert(arrValues.contains("Sam"));
  ask by Prasad translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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

(CodePen验证/使用)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...