Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Array.prototype.includes()

 

includes() 方法用来判断当前数组是否包含某指定的值,如果是,则返回 true,否则返回 false

语法

var boolean = array.includes(searchElement[, fromIndex])

参数

searchElement
需要查找的元素值。
fromIndex
可选参数。从该索引处开始查找 searchElement,默认为 0。

返回值

一个 Boolean

示例

[1, 2, 3].includes(2);     // true
[1, 2, 3].includes(4);     // false
[1, 2, 3].includes(3, 3);  // false
[1, 2, 3].includes(3, -1); // true
[1, 2, NaN].includes(NaN); // true

Polyfill

if (!Array.prototype.includes) {
  Array.prototype.includes = function(searchElement /*, fromIndex*/ ) {
    'use strict';
    if (this == null) {
      throw new TypeError('Array.prototype.includes called on null or undefined');
    }

    var O = Object(this);
    var len = parseInt(O.length, 10) || 0;
    if (len === 0) {
      return false;
    }
    var n = parseInt(arguments[1], 10) || 0;
    var k;
    if (n >= 0) {
      k = n;
    } else {
      k = len + n;
      if (k < 0) {k = 0;}
    }
    var currentElement;
    while (k < len) {
      currentElement = O[k];
      if (searchElement === currentElement ||
         (searchElement !== searchElement && currentElement !== currentElement)) {
        return true;
      }
      k++;
    }
    return false;
  };
}

规范

Specification Status Comment
ECMAScript 2016 (ECMA-262)
Array.prototype.includes
Standard Initial definition.
ECMAScript 2017 Draft (ECMA-262)
Array.prototype.includes
Draft  

浏览器兼容性

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 47 Nightly build 未实现 34 9
Feature Android Android Webview Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support 未实现 47 47 43 未实现 34 9

相关链接

文档标签和贡献者

 此页面的贡献者: Ende93, ziyunfei
 最后编辑者: Ende93,