确定数组是否包含值\[重复\]

JavaScript

村村路易

2020-03-09

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

我正在使用以下功能:

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

第278篇《确定数组是否包含值\[重复\]》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

5个回答
JinJinLEY 2020.03.09
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代表要搜索的元素(用户)。如果要索引,请使用i值

满天星 2020.03.09

另一种选择是通过以下方式使用Array.some如果可用):

Array.prototype.contains = function(obj) {
  return this.some( function(e){ return e === obj } );
}

当且仅当数组中存在与相同的元素时,传递给的匿名函数Array.some才会返回如果没有这样的元素,该函数将不会为数组的任何元素返回,因此也会返回trueobjtrueArray.somefalse

Stafan逆天前端 2020.03.09

给定IE的indexOf的实现(如失明所描述):

Array.prototype.contains = function(obj) {
    return this.indexOf(obj) > -1;
};
飞云卡卡西 2020.03.09

我的一点贡献:

function isInArray(array, search)
{
    return array.indexOf(search) >= 0;
}

//usage
if(isInArray(my_array, "my_value"))
{
    //...
}
飞云泡芙 2020.03.09

jQuery为此具有实用程序功能:

$.inArray(value, array)

返回valuein 中的索引array-1如果array不包含,则返回value

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android