我需要确定数组中是否存在一个值。

我正在使用以下函数:

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

上面的函数总是返回false。

数组值和函数调用如下所示:

arrValues = ["Sam","Great", "Sample", "High"]
alert(arrValues.contains("Sam"));

当前回答

这通常是indexOf()方法的用途。你会说:

return arrValues.indexOf('Sam') > -1

其他回答

jQuery有一个实用函数:

$.inArray(value, array)

返回数组中值的索引。如果数组不包含值,则返回-1。

另参见如何检查数组中是否包含JavaScript对象?

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;
};

你可以这样使用它:

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

CodePen验证/使用

function setFound(){   
 var l = arr.length, textBox1 = document.getElementById("text1");
    for(var i=0; i<l;i++)
    {
     if(arr[i]==searchele){
      textBox1 .value = "Found";
      return;
     }
    }
    textBox1 .value = "Not Found";
return;
}

这个程序检查是否找到给定的元素。Id Text1表示文本框的id, searchele表示要的元素 搜索(得到fron user);如果需要索引,请使用I值

这通常是indexOf()方法的用途。你会说:

return arrValues.indexOf('Sam') > -1

我更喜欢简单:

var days = [1, 2, 3, 4, 5];
if ( 2 in days ) {console.log('weekday');}