提问人:VOZ ESTOICA 提问时间:9/24/2023 最后编辑:OCaVOZ ESTOICA 更新时间:9/26/2023 访问量:83
在 JavaScript 中将列表转换为数组
Convert list to array in JavaScript
问:
此函数意味着将列表转换为数组:
const list = {"value":10,"rest":{"value":20,"rest":null}};
function list_to_array(list) {
arr = [];
for (const property in list) {
if (property == "value") {
arr.push(property);
} else if (property == "rest") {
for (const property in rest) {
arr.push(property);
}
}
}
}
console.log(JSON.stringify(list_to_array(x)));
但是我得到了错误Uncaught ReferenceError ReferenceError: rest is not defined
我怎样才能在 rest 对象中迭代?或者你会如何重写这个函数?
答:
0赞
Draco13
9/24/2023
#1
这条线可以是x = array_to_list([10, 20]);
x = list_to_array([10, 20]);
1赞
Ori Drori
9/24/2023
#2
你需要在这里使用递归,如果你是“休息”。除了获取值外,还使用:property
list[property]
function list_to_array(list) {
const arr = [];
for (const property in list) {
if (property == "value") {
arr.push(list[property]);
} else if (property == "rest") {
arr.push(...list_to_array(list[property])); // call list_to_array on the rest
}
}
return arr; // return the arr
}
const list = {"value":10,"rest":{"value":20,"rest":null}};
const result = list_to_array(list);
console.log(JSON.stringify(result));
但是,您可以缩短递归 - 始终添加值。如果存在,则返回函数的调用 with 和 current 。如果没有,则返回:rest
rest
arr
rest
arr
function list_to_array({ value, rest } = {}, arr = []) {
arr.push(value);
return rest ? list_to_array(rest, arr) : arr;
}
const list = {"value":10,"rest":{"value":20,"rest":null}};
const result = list_to_array(list);
console.log(JSON.stringify(result));
一个更简单的解决方案是使用循环,并在每次迭代时获取属性值:while
rest
function list_to_array(list) {
const arr = [];
let current = list;
do {
arr.push(current?.value);
} while(current = current?.rest);
return arr; // return the arr
}
const list = {"value":10,"rest":{"value":20,"rest":null}};
const result = list_to_array(list);
console.log(JSON.stringify(result));
1赞
Alexander Nenashev
9/24/2023
#3
我建议避免在这里递归,因为大列表很容易溢出堆栈。一个简单的循环将完成任务:while
function list_to_array(list) {
const arr = [list.value];
while(list = list.rest) arr.push(list.value);
return arr;
}
const list = {"value":10,"rest":{"value":20,"rest":null}};
const result = list_to_array(list);
console.log(...result);
评论
rest
list.rest
list['rest']
rest
rest