首页 > JS有什么办法可以快速找出数组里是否有某个值?

JS有什么办法可以快速找出数组里是否有某个值?

JS有什么办法可以快速找出数组里是否有某个值?
这是我常用的方法,感觉好累赘,有没有社么好办法?

function contains(arr, val) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] === val) {
            return true;
        }
    }
}

Array.prototype.in_array = function(search) {
    for(i=0; i<this.length; i++) {
        if(this[i]==search) {
            return true;
        }
    }
    return false;
}

给Array增加一个原型方法,这样所有的数组都通用了,和原生的一些通用Array方法都通用了


jsfunction contains(arr, val) {
  if (arr.indexOf(val) !== -1) {
    return true;
  } else {
    return false;
  }
}

jsArray.prototype.includes()

好吧,这是一个Harmony (ECMAScript 7) proposal。

Polyfill:

jsif (![].includes) {
  Array.prototype.includes = function(searchElement /*, fromIndex*/ ) {
    if (this === undefined || this === null) {
      throw new TypeError('Cannot convert this value to object');
    }
    var O = Object(this);
    var len = parseInt(O.length) || 0;
    if (len === 0) {
      return false;
    }
    var n = parseInt(arguments[1]) || 0;
    var k;
    if (n >= 0) {
      k = n;
    } else {
      k = len + n;
      if (k < 0) k = 0;
    }
    while (k < len) {
      var currentElement = O[k];
      if (searchElement === currentElement ||
         (searchElement !== searchElement && currentElement !== currentElement)) {
        return true;
      }
      k++;
    }
    return false;
  }
}

参考链接:
MDN - Array.prototype.includes()


可以使用array的indexOf方法,参考

JavaScript查找数组是否存在指定元素


http://underscorejs.org/#some

http://underscorejs.org/#contains


var arr = [1, 2, 3, 4, 5, 6, 7];    // array
var wanted = 8;    // any value you want to check

// console.log `true` if found, otherwise `false`
// Browser compatibility: IE9+
console.log(arr.some(function(item) { return item === wanted; }));

// console.log `index` of the value if found, otherwise -1.
// Browser compatibility: IE9+
console.log(arr.indexOf(wanted));
【热门文章】
【热门文章】