我想将嵌套对象列表转换为数组,但是我要返回未定义的数组。
function listToArray(a) {
let list = { value: 1, rest: { value: 2, rest: { value: 3, rest: null } } };
let array = [list.val];
while(list.rest !== null) {
list = list.rest;
array.push(list.val);
}
return array;
}
console.log(listToArray(a));
实际结果是:[undefined,undefined,undefined] 但我想成为这样:[1,2,3]
答案 0 :(得分:1)
您使用的是val
,而不是value
:
function listToArray() {
let list = {value: 1,rest: {value: 2,rest: {value: 3,rest: null}}};
let array = [list.value];
while (list.rest !== null) {
list = list.rest;
array.push(list.value);
}
return array;
}
console.log(listToArray());
或者,您可以使用简单的递归解决方案:
let list = {value: 1,rest: {value: 2,rest: {value: 3,rest: null}}};
function listToArray(obj) {
let result = [obj.value]
if (obj.rest) result = result.concat(listToArray(obj.rest));
return result;
}
console.log(listToArray(list));