I have an issue where I have recursion inside of a for loop:
function func(node) {
for(var i = 0; i < node.children.length; i++) {
func(node.children[i]);
}
}
Obviously because JavaScript does not have block scope, the same i variable is getting modified each time the function is called. What is the best way to remedy this? Assume regular EcmaScript 3 and I can't use JavaScript 1.7 "let".
I know this has been asked before, but the other questions don't seem to show recursion, they show one function call where a closure could be used.
node? JavaScript scopes variables to the containingfunctionor object literal, so each recursive call tofuncshould get its owni.children). Just throw a little code in there that does something tonode, and you're set. Paste this code into the console, and you'll get a nice orange border on everything:function func(node) {for(var i = 0; i < node.children.length; i++) {if(node.nodeType === 1) node.style.border="1px solid orange";func(node.children[i]);}} func(document.body);