Array.prototype.includes()

includes()方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回false。

此方法不会改变数组自身。

此方法是ES6之后的方法。

arr.includes(searchElement, fromIndex)

searchElement

需要查找的元素值

fromIndex

从该索引处开始查找 searchElement。如果为负值,则按升序从 array.length + fromIndex 的索引开始搜索。默认为 0。
[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
如果fromIndex 大于等于数组长度 ,则返回 false 。该数组不会被搜索。
var arr = ['a', 'b', 'c'];

arr.includes('c', 3);   //false
arr.includes('c', 100); // false
如果 fromIndex 为负值,计算出的索引将作为开始搜索searchElement的位置。如果计算出的索引小于 0,则整个数组都会被搜索。
// 数组长度是3
// fromIndex 是 -100
// computed index 是 3 + (-100) = -97

var arr = ['a', 'b', 'c'];

arr.includes('a', -100); // true
arr.includes('b', -100); // true
arr.includes('c', -100); // true
includes() 方法有意设计为通用方法。它不要求this值是数组对象,所以它可以被用于其他类型的对象 (比如类数组对象)。下面的例子展示了 在函数的arguments对象上调用的includes() 方法。
(function() {
  console.log([].includes.call(arguments, 'a')); // true
  console.log([].includes.call(arguments, 'd')); // false
})('a','b','c');
polyfill
if (!Array.prototype.includes) {
    Object.defineProperty(Array.prototype, 'includes', {
      value: function(searchElement, fromIndex) {
  
        // 1. Let O be ? ToObject(this value).
        if (this == null) {//this是空或者未定义,抛出错误
          throw new TypeError('"this" is null or not defined');
        }
  
        var o = Object(this);//将this转变成对象
  
        // 2. Let len be ? ToLength(? Get(O, "length")).
        var len = o.length >>> 0;//无符号右移0位,获取对象length属性,如果未定义就会变成0
  
        // 3. If len is 0, return false.
        if (len === 0) {//length为0直接返回false未找到目标值
          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);//计算正确起始索引,因为有可能是负值
  
        // 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.
          // c. Increase k by 1.
          // NOTE: === provides the correct "SameValueZero" comparison needed here.
          if (o[k] === searchElement) {//如果某一位置与寻找目标相等,返回true,找到了
            return true;
          }
          k++;
        }
  
        // 8. Return false
        return false;//未找到,返回false
      }
    });
  }
此polyfill 没有实现 对于 NaN 的检测。
如果你需要支持那些不支持Object.defineProperty的废弃JavaScript 引擎,你最好不要 polyfill Array.prototype 方法,因为你不能使它们不可枚举。
posted @ 2018-06-25 11:23  hahazexia  阅读(980)  评论(0)    收藏  举报