javascript - 数组如何包含函数在js中工作

标签 javascript

Dose includes function complete loop throw each array item even if required item was in the beginning of array ??谁能解释一下?

$(document).ready(function () {
function search(array,requiredItem) {
   if(array.includes(requiredItem)){
       return true;
   }else{
       return false;
   }
}
search(['alaa','ali','ammar','omar','alia'],'alaa');
});

最佳答案

一旦找到搜索元素,javascript 中的数组包含就会停止。它使用一种称为 SameValueZero 算法的算法。以下是函数 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;
    }
  });
}

关于javascript - 数组如何包含函数在js中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50308054/

相关文章:

javascript - 将 Google 图表下载为 jpeg 而不是 png?

javascript - 如何使用 google apps 脚本划掉电子表格的一行(不是删除它!)?

javascript - 如何将 jquery ui 自动完成功能与 wikimedia opensearch api 一起使用?

javascript - 我想将时间戳与当前时间减去一个月进行比较

javascript - 设置查询以查看对象数组的特定索引

javascript - Ubuntu 11.04 上的 Javascript 使用什么 IDE?

javascript - css 不计算 iPhone 上的所有内容

javascript - 如何删除 javascript 打印函数中的 <a href link>

javascript - React Redux - 调度检索输入值

javascript - 使用 moment.js 如何在一段时间内提供特定格式