javascript - 如何为具有动态嵌套的数组赋值?
问题描述
我正在尝试做这样的事情,但动态地:
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],"好东西"]]
我编写的代码适用于此,但我想在范围可以等于任何数字时动态地(没有开关)(假设数组将始终预先具有该范围,而无需添加新的嵌套)。
解决方案
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; }
推荐阅读
- java - 将 json 转换为 bson 时的性能问题
- python - Python,如何拼接重叠区域的图像?
- android - Edittext 移除 textchangedlistener
- android - 在打盹模式状态下,Android OREO 上的前台服务是否停止了?
- .net - 如何在不破坏 c# 中的代码的情况下重命名一个类
- mysql - 如何合并 4 个表并按 user_id 分组
- python - 如何在 QTreeView 中为具有不同层次列数的模型显示正确的列数
- jquery - 如何在python烧瓶中检索从jquery.get发送的数据
- node.js - 运行命令“ng add @angular/pwa”后无法安装 Sass v4.10
- google-maps - 谷歌地图 ios url 方案留下评论