javascript - When recursion and for loop occur at the same time in js, what is the execution order of the code?
仅有的幸福
仅有的幸福 2017-06-28 09:27:39
0
2
931

function cloneObject(obj){
var o = obj.constructor === Array ? [] : {};
for(var i in obj){
if(obj.hasOwnProperty(i )){
o[i] = typeof obj[i] === "object" ? cloneObject(obj[i]) : obj[i];
}
}
return o;
}
The above code is to implement deep cloning of the object. When the attribute value of the object is an object, the function is recursively executed, that is, only o[i] = typeof obj[i] === " object" ? cloneObject(obj[i]) : obj[i]; When typeof obj[i] === "object" is established, cloneObject(obj[i]) is executed. What I don't understand is that when When executing cloneObject(obj[i]), the cloneObject function is entered again to execute the code, but the for in loop has not ended yet. Should we execute cloneObject first to finish this, and then continue to the next part of the for loop?

仅有的幸福
仅有的幸福

reply all(2)
迷茫

Your recursion is inside the for loop. So when you enter the for loop. The recursion is executed first, and until the recursion returns a result, you return to the for loop to continue execution.

小葫芦

They are all synchronous. The recursive execution must be completed before entering the next for loop

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template