Javascript For Loop Variable And Recursion
Solution 1:
Cache the length of the array so you would have the following:
function recurse(node) {
for(var i = 0, count = node.children.length; i < count; i++) {
recurse(node.children[i]);
}
}
You should always cache especially when you're dealing with HTMLCollections.
Solution 2:
Just use Crockford's walkTheDOM
function:
function walkTheDOM(node, func) {
func(node);
node = node.firstChild;
while (node) {
walkTheDOM(node, func);
node = node.nextSibling;
}
}
You pass in the root node and the function that you want to run for each node, like so:
var root = document.getElementById('wrap');
walkTheDOM(root, function(node) {
console.log( node.nodeName );
});
Live demo:http://jsfiddle.net/VKWTt/
Solution 3:
Was this facing issue, like during recursion of a function the variable values got replaced. the recursion was inside for loop, so the variables inside the for loop where modified.
Use var to declare variables that are modified at recursion.
Solution 4:
I think you example should work. The variable i
is declared local, so when you recurse a new 'i' is used.
Javascript does global and local variables!
Solution 5:
You've already defined 'i' as a variable in a broader scope ;)
Post a Comment for "Javascript For Loop Variable And Recursion"