javascript - React js RangeError:超出最大调用堆栈大小
问题描述
您好我正在尝试使用递归函数来订购数据,这是函数:
function orderRecursive(Data, tab="") {
let orderData = [];
for(const data of Data) {
orderData.push({
id : data.id,
name: tab + data.name,
idfhater : data.idfahter
});
const children = Data.filter( item => item.idfather === data.id);
if( children.length > 0 ){
orderData.push( orderRecursive(children, tab + "\t") );
}
}
return orderData
}
但我遇到了这个麻烦:
RangeError: Maximum call stack size exceeded
类似于函数 rcursive 永远不会结束,但是如果 chlidren > 0 则我有这种情况,否则什么也没发生,所以我不明白为什么会这样?
解决方案
一种解决方案可能是解析数据,以便您拥有包含其他 cat 对象的 cat 对象(快速解决方案)。
// const data = provided data assuming cat id cannot loop indefinitely with father id
// this function creates a dependency tree of cats with root cats and all their children
function getChildren(childrenTree, cat={id: 0}, generation=0) {
const children = []
for(const child of childrenTree.filter(c => c.idfather === cat.id)) {
child.children = getChildren(childrenTree.filter(c => c.idfather !== cat.id), child, generation + 1)
child.generation=generation
children.push(child)
}
return children
}
// this function parses the dependency tree so it prints out whatr you want
function printCats(children, tab="") {
let value = ""
for(const cat of children) {
value += tab + cat.description + "\n";
if(cat.children.length > 0)
value += printCats(cat.children, tab+"\t")
}
return value
}
console.log(printCats(getChildren(data)))
改进
一个更快的选择是将上述两个功能合并为一个:
function printChildren(childrenTree, cat={id: 0}, tab="") {
let childrenStr = ""
for(const child of childrenTree.filter(c => c.idfather === cat.id)) {
childrenStr += `${tab}${child.description}\n`
childrenStr += printChildren(childrenTree.filter(c => c.idfather !== cat.id), child, tab + "\t")
}
return childrenStr
}
console.log(printChildren(data))
这两个代码都打印出来:
Cat
Cat 1
Cat 1.1
Cat 1.2
Cat 2
Cat 2.1
Cat 2.1.1
Cat 2.1.2
Cat 2.1.2.1
Cat 3
此代码使用递归性并且应该是安全的。但是,您应该始终使用递归仔细检查任何代码,因为它可能会使您的内存过载并导致程序崩溃
推荐阅读
- myob - 有没有办法获取有关用户登录的信息?
- django - 由 ... 启动的线程中的未处理异常,在 cmd 中?
- java - 使用 Put.add() 方法在 HBase 中添加值
- sas - SAS Retain 不适用于 1 个字符串变量
- javascript - javascript中的字符串转换
- c# - PreviewMouseUp 事件的 OriginalSource 在不同的控制源上不会改变
- windows - 如何在PowerShell中不断尝试某些东西直到成功?
- azure - 查找使用 python azure-sdk 创建 VM 的应用程序
- three.js - 三 js:禁用精灵的自动旋转
- c# - 外部表不是预期格式