【发布时间】:2018-11-22 10:44:58
【问题描述】:
我正在研究递归函数。
我必须将所有具有键“data: true”的对象推送到一个数组中。 我的函数中间的 console.log 为我提供了单独数组中的所有这些对象。
但我不能在最后返回一个包含对象的数组。 我究竟做错了什么? 谢谢
const entries = {
root: {
data: true,
key: "root",
text: "some text"
},
test: {
one: {
two: {
data: true,
key: "test.one.two",
text: "some text.again"
},
three: {
data: true,
key: "test.one.three",
text: "some.more.text"
}
},
other: {
data: true,
key: "test3",
text: "sometext.text"
}
},
a: {
b: {
data: true,
key: "a.b",
text: "a.b.text"
},
c: {
d: {
data: true,
key: "a.c.d",
text: "some.a.c.d"
}
}
}
};
function recursiveFunc(data) {
let tab = [];
for (let property in data) {
if (data.hasOwnProperty(property)) {
if (data[property].data === true) {
tab.push(data[property]);
console.log("t", tab);
} else {
recursiveFunc(data[property])
}
}
}
return tab
}
console.log(recursiveFunc(entries));
【问题讨论】:
-
嵌套的
recursiveFunc调用不会返回任何内容。 -
您永远不会使用递归调用的结果。只需将其分配给某物并将其推送到原始数组(或连接它,或其他):jsfiddle.net/aco2qryn
-
非常感谢 briosheje,现在可以使用了。我曾尝试过这样的事情,但忘记了传播运算符。
-
没有一个答案纠正了数据为假时的无限递归。
-
@Zim 这不是真的,我上面的小提琴也可以使用
false作为参数。在这种情况下没有无限递归。
标签: javascript function object recursion