您可以在JavaScript中嵌套多少级有限制? [英] Is there a limit to how many levels you can nest in JavaScript?
问题描述
假设您有一个非常复杂的算法,需要数十个for循环.
Say you have this really complex algorithm that requires dozens of for loops.
JavaScript对嵌套的深度循环有限制还是没有限制?
Does JavaScript have a limit to how deep loops can be nested or is there no limit?
深度嵌套for循环的最佳实践是什么?
What is the best practice for deep nested for loops?
我尝试搜索MDN,但找不到我想要的
I tried searching on MDN but couldn't find what I was looking for
编辑
我正在查看是否存在内置限制.例如,如果您有这样的事情
I'm looking if there is a built in limit. For example if you had something like this
If ( a = 1, a < 3, a++) {
if (b = 1; b < 3; b++) {
...
if (cd = 1; cd < 3; cd++)
这实际上有可能还是JS会抛出错误
Would this actually be possible or would JS throw an error
这是您何时需要此功能的理论示例
Here's a theoretical example of when you might need this
您想确定数组中是否有500个数字的总和等于另一个数字.您需要大约500个循环才能将数字添加到组合数组,然后对其进行过滤以找到相对于第三个数字的总和.
You want to find if any 500 numbers in an array sum up to equal another number. You'd need about 500 loops to add the numbers to a combos array and then filter them to find the sum of them relative to a third number.
宇宙中是否还会有足够的空间来存储那么多数据?
Would there even be enough space in the universe to store that much data?
推荐答案
规范中没有限制.由于内存/堆栈溢出,可能在任何实现方式中都将受到限制...
There's no limit in the specification. There will probably be a limit in any implementation due to memory/stack overflows...
例如,这可以正常工作:
For example, this works fine:
var s = 0;
var is = new Array(11);
for(is[0] = 0; is[0] < 2; is[0]++) {
for(is[1] = 0; is[1] < 2; is[1]++) {
for(is[2] = 0; is[2] < 2; is[2]++) {
for(is[3] = 0; is[3] < 2; is[3]++) {
for(is[4] = 0; is[4] < 2; is[4]++) {
for(is[5] = 0; is[5] < 2; is[5]++) {
for(is[6] = 0; is[6] < 2; is[6]++) {
for(is[7] = 0; is[7] < 2; is[7]++) {
for(is[8] = 0; is[8] < 2; is[8]++) {
for(is[9] = 0; is[9] < 2; is[9]++) {
for(is[10] = 0; is[10] < 2; is[10]++) {
s++;
}
}
}
}
}
}
}
}
}
}
}
document.write(s);
这篇关于您可以在JavaScript中嵌套多少级有限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!