Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在JavaScript中检查数组是否包含值?_Javascript_Arrays_Algorithm_Time Complexity_Javascript Objects - Fatal编程技术网

如何在JavaScript中检查数组是否包含值?

如何在JavaScript中检查数组是否包含值?,javascript,arrays,algorithm,time-complexity,javascript-objects,Javascript,Arrays,Algorithm,Time Complexity,Javascript Objects,找出JavaScript数组是否包含值的最简洁有效的方法是什么 这是我知道的唯一方法: function contains(a, obj) { for (var i = 0; i < a.length; i++) { if (a[i] === obj) { return true; } } return false; } 函数包含(a,obj){ 对于(变量i=0;i

找出JavaScript数组是否包含值的最简洁有效的方法是什么

这是我知道的唯一方法:

function contains(a, obj) {
    for (var i = 0; i < a.length; i++) {
        if (a[i] === obj) {
            return true;
        }
    }
    return false;
}
函数包含(a,obj){
对于(变量i=0;i

有没有更好更简洁的方法来实现这一点?

如果您使用的是JavaScript 1.6或更高版本(Firefox 1.5或更高版本),您可以使用。否则,我认为您将得到类似于原始代码的东西。

可能,但它是“ECMA-262标准的JavaScript扩展;因此,它可能不会出现在该标准的其他实现中。”

例如:

[1, 2, 3].indexOf(1) => 0
["foo", "bar", "baz"].indexOf("bar") => 1
[1, 2, 3].indexOf(4) => -1

AFAIC对此表示支持,但如果您愿意,您可以在Internet Explorer(以及其他不支持
indexOf
的浏览器)的阵列中添加类似的功能,例如,作为一个(例如),从2019年开始更新:这个答案是从2008年开始的(11年前!),与现代JS的使用无关。承诺的性能改进是基于当时浏览器中的基准测试。它可能与现代JS执行上下文无关。如果你需要一个简单的解决方案,寻找其他答案。如果您需要最佳性能,请在相关执行环境中为自己设定基准。

正如其他人所说,通过数组进行迭代可能是最好的方法,但可以肯定的是,减少
while
循环是在JavaScript中进行迭代的最快方法。因此,您可能希望按如下方式重写代码:

function contains(a, obj) {
    var i = a.length;
    while (i--) {
       if (a[i] === obj) {
           return true;
       }
    }
    return false;
}
当然,您也可以扩展阵列原型:

Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i] === obj) {
            return true;
        }
    }
    return false;
}
现在,您可以简单地使用以下各项:

alert([1, 2, 3].contains(2)); // => true
alert([1, 2, 3].contains('2')); // => false
Array.prototype.contains = function (v) {
    return this.indexOf(v) > -1;
}

var a = [ 'foo', 'bar' ];

a.contains('foo'); // true
a.contains('fox'); // false
下面是
Array.indexOf
的一个实现:

if (!Array.indexOf) {
    Array.indexOf = [].indexOf ?
        function(arr, obj, from) {
            return arr.indexOf(obj, from);
        } :
        function(arr, obj, from) { // (for IE6)
            var l = arr.length,
                i = from ? parseInt((1 * from) + (from < 0 ? l : 0), 10) : 0;
            i = i < 0 ? 0 : i;
            for (; i < l; i++) {
                if (i in arr && arr[i] === obj) {
                    return i;
                }
            }
            return -1;
        };
}
if(!Array.indexOf){
Array.indexOf=[].indexOf?
功能(arr、obj、from){
返回arr.indexOf(obj,from);
} :
函数(arr、obj、from){//(对于IE6)
var l=阵列长度,
i=from?parseInt((1*from)+(from<0?l:0),10):0;
i=i<0?0:i;
对于(;i
扩展JavaScript
数组
对象是一个非常糟糕的主意,因为在
for in
循环中引入了新属性(自定义方法),这可能会破坏现有脚本。几年前,该库的作者不得不重新设计其库实现,以删除此类内容

如果你不需要担心与页面上运行的其他JavaScript的兼容性,那就去做吧,否则,我会推荐更笨拙但更安全的独立函数解决方案。

现代浏览器都有,这正是除IE之外的所有人都能做到的:


console.log(['joe','jane','mary'])。包括('jane')//真的
先开箱思考一下,如果您多次进行此调用,使用关联数组和映射来使用哈希函数进行查找要高效得多


如果您反复检查数组中是否存在对象,您可能应该查看

  • 通过在数组中执行操作(将新对象放在正确的位置),始终保持数组的排序
  • 将更新对象设为删除+排序插入操作,然后
  • 包含(a,obj)
    中使用查找

  • 假设您定义了这样一个数组:

    const array = [1, 2, 3, 4]
    
    下面是检查是否有
    3
    的三种方法。它们都返回
    true
    false

    本机数组方法(自ES2016起)() 作为自定义数组方法(ES2016之前) 简单函数 而
    array.indexOf(x)=-1
    是实现这一点的最简洁的方法(非InternetExplorer浏览器已经支持了十多年…),它不是O(1),而是O(N),这很糟糕。如果您的数组不会更改,您可以将数组转换为哈希表,然后执行
    table[x]==未定义的
    ==未定义的

    Array.prototype.toTable = function() {
        var t = {};
        this.forEach(function(x){t[x]=true});
        return t;
    }
    
    演示:

    (不幸的是,虽然您可以创建Array.prototype.contains来“冻结”数组并在其中存储哈希表。_缓存为两行,如果您以后选择编辑数组,这将给出错误的结果。JavaScript没有足够的钩子让您保持这种状态,例如与Python不同。

    函数inArray(elem,Array)
    {
    var len=array.length;
    对于(变量i=0;i
    如果找到,则返回数组索引;如果未找到,则返回-1使用:

    function isInArray(array, search)
    {
        return array.indexOf(search) >= 0;
    }
    
    // Usage
    if(isInArray(my_array, "my_value"))
    {
        //...
    }
    
    使用:


    要确切了解
    tilde在这一点上做了什么,请参考此问题。

    ECMAScript 6有一个关于查找的优雅建议

    find方法对每个元素执行一次回调函数 存在于数组中,直到找到回调返回true的数组为止 价值如果找到这样的元素,find将立即返回该值 这一因素的影响。否则,find返回undefined。回调是 仅对具有赋值的数组索引调用;信息技术 不会为已删除或从未删除的索引调用 已分配值

    这是关于那件事的答案

    查找功能的工作原理如下

    function isPrime(element, index, array) {
        var start = 2;
        while (start <= Math.sqrt(element)) {
            if (element % start++ < 1) return false;
        }
        return (element > 1);
    }
    
    console.log( [4, 6, 8, 12].find(isPrime) ); // Undefined, not found
    console.log( [4, 5, 8, 12].find(isPrime) ); // 5
    
    函数isPrime(元素、索引、数组){
    var启动=2;
    while(启动1);
    }
    console.log([4,6,8,12].find(isPrime));//未定义,未找到
    console.log([4,5,8,12].find(isPrime));//5.
    
    您可以在ECMAScript 5及以下版本中使用它

    if(!Array.prototype.find){
    Object.defineProperty(Array.prototype,“find”{
    可枚举:false,
    对,,
    可写:对,
    值:函数(谓词){
    if(this==null){
    抛出新的TypeError('Array.pro
    
    var toRemove = [2,4].toTable();
    [1,2,3,4,5].filter(function(x){return toRemove[x]===undefined})
    
    function inArray(elem,array)
    {
        var len = array.length;
        for(var i = 0 ; i < len;i++)
        {
            if(array[i] == elem){return i;}
        }
        return -1;
    } 
    
    function isInArray(array, search)
    {
        return array.indexOf(search) >= 0;
    }
    
    // Usage
    if(isInArray(my_array, "my_value"))
    {
        //...
    }
    
    var myArray = ['yellow', 'orange', 'red'] ;
    
    alert(!!~myArray.indexOf('red')); //true
    
    function isPrime(element, index, array) {
        var start = 2;
        while (start <= Math.sqrt(element)) {
            if (element % start++ < 1) return false;
        }
        return (element > 1);
    }
    
    console.log( [4, 6, 8, 12].find(isPrime) ); // Undefined, not found
    console.log( [4, 5, 8, 12].find(isPrime) ); // 5
    
    if (!Array.prototype.find) {
      Object.defineProperty(Array.prototype, 'find', {
        enumerable: false,
        configurable: true,
        writable: true,
        value: function(predicate) {
          if (this == null) {
            throw new TypeError('Array.prototype.find called on null or undefined');
          }
          if (typeof predicate !== 'function') {
            throw new TypeError('predicate must be a function');
          }
          var list = Object(this);
          var length = list.length >>> 0;
          var thisArg = arguments[1];
          var value;
    
          for (var i = 0; i < length; i++) {
            if (i in list) {
              value = list[i];
              if (predicate.call(thisArg, value, i, list)) {
                return value;
              }
            }
          }
          return undefined;
        }
      });
    }
    
    Array.prototype.contains = function (v) {
        return this.indexOf(v) > -1;
    }
    
    var a = [ 'foo', 'bar' ];
    
    a.contains('foo'); // true
    a.contains('fox'); // false
    
    const items = [ {a: '1'}, {a: '2'}, {a: '3'} ]
    
    items.some(item => item.a === '3')  // returns true
    items.some(item => item.a === '4')  // returns false
    
    if (items.some(item => item.a === '3')) {
      // do something
    }
    
    /*
     * @function
     * @name Object.prototype.inArray
     * @description Extend Object prototype within inArray function
     *
     * @param {mix}    needle       - Search-able needle
     * @param {bool}   searchInKey  - Search needle in keys?
     *
     */
    Object.defineProperty(Object.prototype, 'inArray',{
        value: function(needle, searchInKey){
    
            var object = this;
    
            if( Object.prototype.toString.call(needle) === '[object Object]' || 
                Object.prototype.toString.call(needle) === '[object Array]'){
                needle = JSON.stringify(needle);
            }
    
            return Object.keys(object).some(function(key){
    
                var value = object[key];
    
                if( Object.prototype.toString.call(value) === '[object Object]' || 
                    Object.prototype.toString.call(value) === '[object Array]'){
                    value = JSON.stringify(value);
                }
    
                if(searchInKey){
                    if(value === needle || key === needle){
                    return true;
                    }
                }else{
                    if(value === needle){
                        return true;
                    }
                }
            });
        },
        writable: true,
        configurable: true,
        enumerable: false
    });
    
    var a = {one: "first", two: "second", foo: {three: "third"}};
    a.inArray("first");          //true
    a.inArray("foo");            //false
    a.inArray("foo", true);      //true - search by keys
    a.inArray({three: "third"}); //true
    
    var b = ["one", "two", "three", "four", {foo: 'val'}];
    b.inArray("one");         //true
    b.inArray('foo');         //false
    b.inArray({foo: 'val'})   //true
    b.inArray("{foo: 'val'}") //false
    
    var c = "String";
    c.inArray("S");        //true
    c.inArray("s");        //false
    c.inArray("2", true);  //true
    c.inArray("20", true); //false
    
    function contains(a, obj) {
        return a.some(function(element){return element == obj;})
    }
    
    function contains(arr, x) {
        return arr.filter(function(elem) { return elem == x }).length > 0;
    }
    
    function bidirectionalIndexOf(a, b, c, d, e){
      for(c=a.length,d=c*1; c--; ){
        if(a[c]==b) return c; //or this[c]===b
        if(a[e=d-1-c]==b) return e; //or a[e=d-1-c]===b
      }
      return -1
    }
    
    //Usage
    bidirectionalIndexOf(array,'value');
    
    Object.defineProperty(Array.prototype,'bidirectionalIndexOf',{value:function(b,c,d,e){
      for(c=this.length,d=c*1; c--; ){
        if(this[c]==b) return c; //or this[c]===b
        if(this[e=d-1-c] == b) return e; //or this[e=d-1-c]===b
      }
      return -1
    },writable:false, enumerable:false});
    
    // Usage
    array.bidirectionalIndexOf('value');
    
    function bidirectionalIndexOf(a, b, c, d){
      c=a.length; d=c-1;
      while(c--){
        if(b===a[c]) return c;
        if(b===a[d-c]) return d-c;
      }
      return c
    }
    
    // Usage
    bidirectionalIndexOf(array,'value');
    
    $.inArray({'b': 2}, [{'a': 1}, {'b': 2}])
    > -1
    
    _.some([{'a': 1}, {'b': 2}], {'b': 2})
    > true
    
    $.inArray(2, [1,2])
    > 1
    
    (_.isObject(item)) ? _.some(ary, item) : (_.indexOf(ary, item) > -1)
    
    function contains(arr, obj) {
      const stringifiedObj = JSON.stringify(obj); // Cache our object to not call `JSON.stringify` on every iteration
      return arr.some(item => JSON.stringify(item) === stringifiedObj);
    }
    
    contains([{a: 1}, {a: 2}], {a: 1}); // true
    
    function contains(arr, obj) {
      var stringifiedObj = JSON.stringify(obj)
      return arr.some(function (item) {
        return JSON.stringify(item) === stringifiedObj;
      });
    }
    
    // .some polyfill, not needed for IE9+
    if (!('some' in Array.prototype)) {
      Array.prototype.some = function (tester, that /*opt*/) {
        for (var i = 0, n = this.length; i < n; i++) {
          if (i in this && tester.call(that, this[i], i, this)) return true;
        } return false;
      };
    }
    
    contains([{a: 1}, {a: 2}], {a: 1}); // true
    
    [{a: 1}, {a: 2}].includes({a: 1});
    // false, because {a: 1} is a new object
    
    [{a: 1}, {a: 2}].some(item => JSON.stringify(item) === JSON.stringify({a: 1));
    // true
    
    function contains(a, obj) {
        for (var i = 0; i < a.length; i++) {
            if (JSON.stringify(a[i]) === JSON.stringify(obj)) {
                return true;
            }
        }
        return false;
    }
    
    let obj = { name: 'Sumer', age: 36 };
    let arrObj = [obj, { name: 'Kishor', age: 46 }, { name: 'Rupen', age: 26 }];
    
    
    console.log(arrObj.indexOf(obj));// 0
    console.log(arrObj.indexOf({ name: 'Sumer', age: 36 })); //-1
    
    console.log([1, 3, 5, 2].indexOf(2)); //3
    
    console.log(arrObj.includes(obj));  //true
    console.log(arrObj.includes({ name: 'Sumer', age: 36 })); //false
    
    console.log([1, 3, 5, 2].includes(2)); //true
    
    console.log(arrObj.find(e => e.age > 40));  //{ name: 'Kishor', age: 46 }
    console.log(arrObj.find(e => e.age > 40)); //{ name: 'Kishor', age: 46 }
    
    console.log([1, 3, 5, 2].find(e => e > 2)); //3
    
    console.log(arrObj.findIndex(e => e.age > 40));  //1
    console.log(arrObj.findIndex(e => e.age > 40)); //1
    
    console.log([1, 3, 5, 2].findIndex(e => e > 2)); //1
    
    var users = [{id: "101", name: "Choose one..."},
    {id: "102", name: "shilpa"},
    {id: "103", name: "anita"},
    {id: "104", name: "admin"},
    {id: "105", name: "user"}];
    
    let data = users.find(object => object['id'] === '104');
    
    {id: "104", name: "admin"}
    
    let indexToUpdate = users.indexOf(data);
    let newObject = {id: "104", name: "customer"};
    users[indexToUpdate] = newObject;//your new object
    console.log(users);
    
    [{id: "101", name: "Choose one..."},
    {id: "102", name: "shilpa"},
    {id: "103", name: "anita"},
    {id: "104", name: "customer"},
    {id: "105", name: "user"}];