首页 > 解决方案 > 如何为具有动态嵌套的数组赋值?

问题描述

我正在尝试做这样的事情,但动态地:

switch (scope) {
    case 1: array.push("something nice"); break;
    case 2: array[array.length-1].push("something nice"); break;
    case 3: array[array[array.length-1].length-1].push("something nice"); break;
    case 4: ...you get the idea
}

这意味着,如果我有一个这样的数组:

[1,2,[5,3,9,[4]]]

当范围= 3时我输入开关,结果将是:

[1,2,[5,3,9,[4,"好东西"]]]

但是,如果 scope = 2,结果将是:

[1,2,[5,3,9,[4],"好东西"]]

我编写的代码适用于此,但我想在范围可以等于任何数字时动态地(没有开关)(假设数组将始终预先具有该范围,而无需添加新的嵌套)。

标签: javascriptarrays

解决方案


scope如果是一个,您可以进行递归并推送。

(个人认为,从编程的意义上讲,基于零的范围界定会更自然。)

function push(array, scope, value) {
    if (scope === 1) return array.push(value);
    push(array[array.length - 1], scope - 1, value);
}

const array = [1, 2, [5, 3, 9, [4]]];

push(array, 3, 'something nice');

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }


推荐阅读