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

我正在使用以下函数:

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"));

当前回答

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值

其他回答

jQuery有一个实用函数:

$.inArray(value, array)

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

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

从ECMAScript6开始,可以使用Set:

var myArray = ['A', 'B', 'C'];
var mySet = new Set(myArray);
var hasB = mySet.has('B'); // true
var hasZ = mySet.has('Z'); // false

答案对我来说并不管用,但它给了我一个想法:

Array.prototype.contains = function(obj)
    {
        return (this.join(',')).indexOf(obj) > -1;
    }

它并不完美,因为在分组之外相同的项目最终可能是匹配的。比如我的例子

var c=[];
var d=[];
function a()
{
    var e = '1';
    var f = '2';
    c[0] = ['1','1'];
    c[1] = ['2','2'];
    c[2] = ['3','3'];
    d[0] = [document.getElementById('g').value,document.getElementById('h').value];

    document.getElementById('i').value = c.join(',');
    document.getElementById('j').value = d.join(',');
    document.getElementById('b').value = c.contains(d);
}

当我调用这个函数时,'g'和'h'字段分别包含1和2,它仍然能找到它,因为连接的结果字符串是:1,1,2,2,3,3

因为在我的情况下,我不确定是否会遇到这种情况,所以我使用了这个。我想我应该分享一下,以防其他人也不能做出选择的答案。

使用像lodash这样的库几乎总是更安全,因为存在跨浏览器兼容性和效率方面的所有问题。

效率,因为你可以保证在任何给定的时间,一个非常流行的库,如下划线,将有最有效的方法来完成这样的效用函数。

_.includes([1, 2, 3], 3); // returns true

如果你担心通过包含整个库而添加到应用程序中的大量内容,那么你可以单独包含功能:

var includes = require('lodash/collections/includes');

注意:在旧版本的lodash中,这是_.contains()而不是_.includes()。

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验证/使用