JavaScript for循环首次赋值前触发浏览器崩溃问题排查求助
问题根因
- 循环变量未声明块级作用域:你的代码中
for(child of Object.values(folder.children))、for(location of Object.values(fileTree))两处循环的迭代变量都没有加let/const声明,默认会成为全局变量。递归执行renderFolder的过程中,同一个全局变量会被反复赋值覆盖,直接导致逻辑混乱进入死循环,浏览器内存被占满后触发崩溃。你调试时看到的赋值瞬间崩溃,本质就是首次全局变量赋值触发了后续的死循环逻辑。 - 递归函数
this指向错误:renderFolder是普通函数声明,直接调用时内部this默认指向全局window对象,如果你原本的createCatelogFolder、createCatelogFile是挂载在当前实例上的方法,此处调用会直接触发未定义报错,也可能导致异常逻辑崩溃。
修复方案
基础兼容版代码
HGEClient.send("queryfiletree").then(fileTree => { // 提前存储外层上下文,避免this指向偏移 const that = this; let renderFolder = function(parentFolder, folder) { that.createCatelogFolder(parentFolder, folder); // 给迭代变量加const声明块级作用域 for(const child of Object.values(folder.children)) if(child.type == "folder") renderFolder(folder, child); else that.createCatelogFile(folder, child); } // 给迭代变量加const声明块级作用域 for(const location of Object.values(fileTree)) if(location.type == "folder") renderFolder(null, location); else that.createCatelogFile(null, location); });
箭头函数简化版(兼容ES6+环境)
箭头函数会自动绑定外层this,不需要额外存储上下文变量:
HGEClient.send("queryfiletree").then(fileTree => { const renderFolder = (parentFolder, folder) => { this.createCatelogFolder(parentFolder, folder); for(const child of Object.values(folder.children)) child.type == "folder" ? renderFolder(folder, child) : this.createCatelogFile(folder, child); } for(const location of Object.values(fileTree)) location.type == "folder" ? renderFolder(null, location) : this.createCatelogFile(null, location); });
内容的提问来源于stack exchange,提问作者小奥利奥
相关产品推荐
相关产品推荐

