polyfill.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. if (!Array.prototype.at) {
  2. // eslint-disable-next-line no-extend-native
  3. Object.defineProperty(Array.prototype, 'at', {
  4. value: function (index) {
  5. // 将索引转换为整数
  6. index = Math.trunc(index) || 0;
  7. // 如果索引为负数,则从数组末尾开始计算索引位置
  8. if (index < 0) {
  9. index += this.length;
  10. }
  11. // 如果索引越界,则返回 undefined
  12. if (index < 0 || index >= this.length) {
  13. return undefined;
  14. }
  15. // 返回指定索引位置的元素
  16. return this[index];
  17. },
  18. enumerable: false,
  19. configurable: true,
  20. writable: true
  21. });
  22. }
  23. if (typeof ArrayBuffer !== 'undefined' && !ArrayBuffer.hasOwnProperty('byteLength')) {
  24. Object.defineProperty(ArrayBuffer, 'byteLength', {
  25. get: function () {
  26. return this.byteLength || this.length;
  27. }
  28. });
  29. }
  30. if (typeof structuredClone === "undefined") {
  31. // 如果浏览器不支持 structuredClone 方法,则定义一个备用方法
  32. function structuredClone(obj) {
  33. if (obj === null || typeof obj !== "object") {
  34. return obj;
  35. }
  36. if (Array.isArray(obj)) {
  37. return obj.map(structuredClone);
  38. }
  39. if (obj instanceof ArrayBuffer || ArrayBuffer.isView(obj)) {
  40. return obj.slice(0);
  41. }
  42. const cloned = Object.create(Object.getPrototypeOf(obj));
  43. const props = Object.getOwnPropertyNames(obj);
  44. props.forEach((prop) => {
  45. const descriptor = Object.getOwnPropertyDescriptor(obj, prop);
  46. if (descriptor) {
  47. descriptor.value = structuredClone(descriptor.value);
  48. Object.defineProperty(cloned, prop, descriptor);
  49. }
  50. });
  51. return cloned;
  52. }
  53. }