优化数组循环 收尾循环

// 在这里处理每个元素,根据你的需求进行相应的操作
// eslint-disable-next-line no-extend-native
Array.prototype.doubleProcess = function (processItem = () => {
}) {
  if (this.length < 2) {
    // 如果数组长度小于2,直接处理所有元素
    for (let i = 0; i < this.length; i++) {
      processItem(this[i], i);
    }
  } else {
    // 如果数组长度大于等于2,首尾取值并处理
    for (let i = 0; i < this.length - 1; i += 2) {
      processItem(this[i], i);
      processItem(this[i + 1], i + 1);
    }
    // 如果数组长度是奇数,额外处理最后一个元素
    if (this.length % 2 !== 0) {
      processItem(this[this.length - 1], this.length - 1);
    }
  }
};

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容