递归,规律一眼可见,写出了前面3条,怎么改成递归

问题描述

image.png

            if (index.length === 1) {
              listRight.splice(index[0] + 1 , 0 ,copyValue)
            }
            if (index.length === 2) {
              listRight[index[0]].tasks.splice(index[1] + 1,0,copyValue)
            }
            if (index.length === 3) {
              listRight[index[0]].tasks[index[1]].tasks.splice(index[2] + 1,0,copyValue)
            }

image.png

阅读 2.3k
3 个回答

我猜你想要这个

let fn = (index, listRight, copyValue) => {
  [0, ...index.slice(0, -1)]
    .reduce((tag, i) => tag[i]["tasks"], [{ tasks: listRight }])
    .splice(index.slice(-1) + 1, 0, copyValue);
  return listRight;
};
fn(
  [0, 0, 1],
  [{
    tasks: [{
      tasks: [
        {id: 5, tasks: []},
        {id: 7, tasks: []}
      ]
    }]
  }],
  { id: 6, tasks: [] }
);

Array 构造函数默认行为造成的

Array(1,2)// 有多个参数的时候 返回 [1,2] 数组
Array(1) // 只有一个参数的时候 返回长度为1的数组=> [empty]
/*这里把*/Array(0, ...index.slice(0, -1))/*改成*/
[0, ...index.slice(0, -1))] /*就行了*/

看起来最直观的是用循环解决。

let tasks = listRight
while (index.length > 1) tasks = tasks[index.shift()]
index.length && tasks.splice(index[0] + 1, 0, copyValue)

修改了一下答案:

        let listRight = [];
        function func(index, currentIndex, result, copyValue) {
            const length = index.length;
            if (currentIndex === length - 1) {
                // 最后一个
                result.splice(index[length - 1] + 1, 0, copyValue)
            } else {
                currentIndex++;
                result = result[index[currentIndex]].tasks;
                return func(index, currentIndex, result, copyValue);
            }
        }
        let index = [];
        const currentIndex = 0;
        let result = [];
        let copyValue = "test";
        func(index, currentIndex, result, copyValue);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题