【发布时间】:2020-04-05 01:45:54
【问题描述】:
“编写一个函数arrayToList,构建一个类似的列表结构”
让 LL = { data: 1, next: { data: 2, next: { data: 3, next: null }}};
我了解这个问题的典型解决方案,列表必须由内而外构建:
function arrToLList(arr) {
let LList = null;
for (let i = arr.length - 1; i >= 0; i--) {
LList = { data: arr[i], next: LList };
}
return LList;
}
但我最初的解决方案是使用典型的 for 循环强制它。
function arrayToLList(arr) {
let d = "data";
let n = "next";
let LList = nextNode();
for (let i = 0; i < arr.length; i++) {
LList[d] = arr[i];
d = "next." + d;
LList[n] = nextNode();
n = "next." + n;
}
function nextNode() {
return {
data: null,
next: null
};
}
return LList;
}
【问题讨论】:
-
如果您实现this question 的答案之一或使用lodash
get方法,您的解决方案就可以工作 -
抱歉,您需要的是 lodash set 方法
标签: javascript data-structures nested javascript-objects