如果数组列表太大,为什么以下递归代码会导致堆栈溢出?我该如何解决这个问题仍然保留递归模式?
var list = readHugeList();
var nextListItem = function() {
var item = list.pop();
if (item) {
// process the list item...
nextListItem();
}
};
Run Code Online (Sandbox Code Playgroud)
这听起来很奇怪,但使用setTimeout.
像这样:
//fill it with 50000 elements
var list = Array(50001).join('1.1').split('.');
var nextListItem = function() {
var item = list.pop();
if (item) { //should be list.length
// recursion here!
setTimeout( nextListItem, 0 );
}
};
nextListItem();
Run Code Online (Sandbox Code Playgroud)
现在的递归是无止境的!
请注意,有些浏览器不喜欢0那里。
作为副作用,您的代码不会阻止浏览器。
| 归档时间: |
|
| 查看次数: |
1470 次 |
| 最近记录: |