array-includes.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. define([], function() {
  2. // https://tc39.github.io/ecma262/#sec-array.prototype.includes
  3. if (!Array.prototype.includes) {
  4. Object.defineProperty(Array.prototype, 'includes', {
  5. value: function (searchElement, fromIndex) {
  6. if (this == null) {
  7. throw new TypeError('"this" is null or not defined');
  8. }
  9. // 1. Let O be ? ToObject(this value).
  10. var o = Object(this);
  11. // 2. Let len be ? ToLength(? Get(O, "length")).
  12. var 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. var 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. var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
  26. function sameValueZero(x, y) {
  27. return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
  28. }
  29. // 7. Repeat, while k < len
  30. while (k < len) {
  31. // a. Let elementK be the result of ? Get(O, ! ToString(k)).
  32. // b. If SameValueZero(searchElement, elementK) is true, return true.
  33. if (sameValueZero(o[k], searchElement)) {
  34. return true;
  35. }
  36. // c. Increase k by 1.
  37. k++;
  38. }
  39. // 8. Return false
  40. return false;
  41. }
  42. });
  43. }
  44. })