ECMAScript 2016: Array.prototype.includes() 方法介绍

348 阅读2分钟

原文地址:ECMAScript 2016: Array.prototype.includes(),2016.02.03,by Marius Schulz

Array.prototype.includes() 方法定义在 Array 原型上,是 ECMAScript 2016 标准引入的两个新特性之一。Array.prototype.includes() 查找数组是否包含给定元素,并返回 truefalse

另一个新特性是 指数运算符 **,为 Math.pow 的使用提供了一些语法糖。

Array.prototype.includes() vs. Array.prototype.indexOf()

直到现在,你可能一直将 Array.prototype.indexOf() 方法的返回值与 -1 进行比较,以查找数组中是否包含某个值:

const numbers = [4, 8, 15, 16, 23, 42];

if (numbers.indexOf(42) !== -1) {
  // ...
}

Array.prototype.includes() 方法让这个查找更易读,对人来说更有语义意义:

const numbers = [4, 8, 15, 16, 23, 42];

if (numbers.includes(42)) {
  // ...
}

这里的 if 判断读起来几乎像一个普通的英语句子。不需要再为确定是否是数组成员而纠结于索引值。

查找 NaN

然而,有一种边缘情况,indexOfincludes 的行为不同,那就是 NaN。因为严格比较 NaN === NaN 返回 false,所以在数组中搜索 NaN 时,indexOf 方法将返回 -1

assert([NaN].indexOf(NaN) === -1);

大多数情况下,这可能不是你想要的。includes 方法可以解决此问题并返回 true

assert([NaN].includes(NaN) === true);

正如期望的那样,有符号零值 +0-0 仍然被看作是相同的:

assert([+0].includes(-0) === true);
assert([-0].includes(+0) === true);

提供起始索引

indexOf 方法接受一个可选的第二个参数,名为 fromIndex,它指定从数组中的哪个索引开始查找:

assert([100, 200, 300].indexOf(100, 0) === 0);
assert([100, 200, 300].indexOf(100, 1) === -1);

为了保持一致性,includes 方法也接受此参数:

assert([100, 200, 300].includes(100, 0) === true);
assert([100, 200, 300].includes(100, 1) === false);

Array.prototype.includes() 的 Polyfill

MDN 上还提供了符合规范的 polyfill,可以让你今天就使用 Array.prototype.includes() 而不用担心浏览器兼容性问题:

// https://tc39.github.io/ecma262/#sec-array.prototype.includes
if (!Array.prototype.includes) {
  Object.defineProperty(Array.prototype, "includes", {
    value: function (searchElement, fromIndex) {
      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      // 1. Let O be ? ToObject(this value).
      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If len is 0, return false.
      if (len === 0) {
        return false;
      }

      // 4. Let n be ? ToInteger(fromIndex).
      //    (If fromIndex is undefined, this step produces the value 0.)
      var n = fromIndex | 0;

      // 5. If n ≥ 0, then
      //  a. Let k be n.
      // 6. Else n < 0,
      //  a. Let k be len + n.
      //  b. If k < 0, let k be 0.
      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

      function sameValueZero(x, y) {
        return (
          x === y ||
          (typeof x === "number" &&
            typeof y === "number" &&
            isNaN(x) &&
            isNaN(y))
        );
      }

      // 7. Repeat, while k < len
      while (k < len) {
        // a. Let elementK be the result of ? Get(O, ! ToString(k)).
        // b. If SameValueZero(searchElement, elementK) is true, return true.
        if (sameValueZero(o[k], searchElement)) {
          return true;
        }
        // c. Increase k by 1.
        k++;
      }

      // 8. Return false
      return false;
    },
  });
}

进一步阅读

更多细节请查看 Domenic Denicola 和 Rick Waldron 的 原始特性提案当前的规范草案 或者 MDN 上的文档