Array.includes.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // https://tc39.github.io/ecma262/#sec-array.prototype.includes
  2. if (!Array.prototype.includes) {
  3. // eslint-disable-next-line no-extend-native
  4. Object.defineProperty(Array.prototype, "includes", {
  5. value: function (searchElement, fromIndex) {
  6. // 1. Let O be ? ToObject(this value).
  7. if (this == null) {
  8. throw new TypeError('"this" is null or not defined');
  9. }
  10. const o = Object(this),
  11. // 2. Let len be ? ToLength(? Get(O, "length")).
  12. len = o.length >>> 0;
  13. // 3. If len is 0, return false.
  14. if (len === 0) {
  15. return false;
  16. }
  17. // 4. Let n be ? ToInteger(fromIndex).
  18. // (If fromIndex is undefined, this step produces the value 0.)
  19. let n = fromIndex | 0,
  20. // 5. If n ≥ 0, then
  21. // a. Let k be n.
  22. // 6. Else n < 0,
  23. // a. Let k be len + n.
  24. // b. If k < 0, let k be 0.
  25. k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
  26. // 7. Repeat, while k < len
  27. while (k < len) {
  28. // a. Let elementK be the result of ? Get(O, ! ToString(k)).
  29. // b. If SameValueZero(searchElement, elementK) is true, return true.
  30. // c. Increase k by 1.
  31. // NOTE: === provides the correct "SameValueZero" comparison needed here.
  32. if (o[k] === searchElement) {
  33. return true;
  34. }
  35. k++;
  36. }
  37. // 8. Return false
  38. return false;
  39. }
  40. });
  41. }