JavaScript 数据结构索引设置函数优化

本文介绍一种使用 ES6 语法优化 JavaScript 数据结构索引设置函数的方法,提高代码可读性和效率。

原始代码:

function setIndex (data) {
    let queue = [...data];
    let loop = 0;
    while (queue.length > 0) {
        loop++
        [...queue].forEach((child, i) => {
            queue.shift()
            if (loop == 1) {
                child.customIndex = i + 1 + '';
                child.currentIndex = i;
                child.path = i;
            }
            if (child.children && child.children.length > 0) {
                child.dataType = 1
                for (let ci = 0; ci < child.children.length; ci++) {
                    child.children[ci].currentIndex = ci
                    child.children[ci].customIndex = child.customIndex + '.' + (ci + 1)
                    child.children[ci].path = child.path + '.children.' + ci;
                }
                queue.push(...child.children)
            } else {
                child.dataType = 2
            }
        })
    }
}

使用 ES6 优化后的代码:

function setIndex(data) {
  let queue = [...data];
  let loop = 0;
  while (queue.length > 0) {
    loop++;
    queue.forEach((child, i) => {
      queue.shift();
      if (loop == 1) {
        child.customIndex = `${i + 1}`;
        child.currentIndex = i;
        child.path = i;
      }
      if (child.children && child.children.length > 0) {
        child.dataType = 1;
        child.children.forEach((grandChild, ci) => {
          grandChild.currentIndex = ci;
          grandChild.customIndex = `${child.customIndex}.${ci + 1}`;
          grandChild.path = `${child.path}.children.${ci}`;
        });
        queue.push(...child.children);
      } else {
        child.dataType = 2;
      }
    });
  }
}

优化后的代码主要做了以下改变:

  • 使用 ES6 模板字符串简化字符串拼接操作,提高代码可读性。
  • 使用 forEach 循环遍历子节点,避免使用 for 循环。
  • 使用 queue.shift() 方法从队列中移除当前节点,提高效率。
  • 使用 ES6 展开运算符 ... 简化代码逻辑。

通过这些优化,代码更简洁、易于理解和维护,同时提高了代码效率。

JavaScript 数据结构索引设置函数优化

原文地址: https://www.cveoy.top/t/topic/oPdO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录