Rob*_*yan 3 javascript recursion object
我有一个带有嵌套对象的对象:
let list = {
value: 1,
next: {
value: 2,
next: {
value: 3,
next: {
value: 4,
next: null
}
}
}
};
Run Code Online (Sandbox Code Playgroud)
我需要返回所有key: value,list我必须使用递归。我试图将嵌套对象推送到函数中的局部变量,但在第二次迭代中失败,因为名称不同。
这是函数:
function printList(list){
let nested = {};
if(list.hasOwnProperty('next')) {
nested = list.next;
printList(nested);
} else {
return nested;
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法用递归解决它?
它应该返回value属性。在这种情况下
1
2
3
4
Run Code Online (Sandbox Code Playgroud)
您可以返回一个包含值的数组并在检查后获取嵌套值
function printList({ value, next }) {
return [value, ...(next ? printList(next) : [])]
}
let list = { value: 1, next: { value: 2, next: { value: 3, next: { value: 4, next: null } } } };
console.log(printList(list));Run Code Online (Sandbox Code Playgroud)