can somebody explain this code? I don't get what is inside the "for" structure.
var tree = {}
function addToTree(tree, array) {
for (var i = 0, length = array.length; i < length; i++) {
tree = tree[array[i]] = tree[array[i]] || {}
}
}
addToTree(tree, ["a", "b", "c"])
addToTree(tree, ["a", "b", "d"])
/*{
"a": {
"b": {
"c": {},
"d": {}
}
}
}*/
I've expanded the body of the for
loop and added some comments in attempt to make things more explicit.
for (var i = 0, length = array.length; i < length; i++) {
// Assign the current item in the array to a variable
var current = array[i];
// If there is no property on the "tree" object corresponding to the value of
// "current", set this property to a new object
if (!tree[current]) {
tree[current] = {};
}
// Set the "tree" variable to the field in the "tree" object whose
// name corresponds to "current". On the next loop iteration, "tree" will
// refer to this "child" object, resulting in a tree-like object being
// created as we iterate.
tree = tree[current];
}
That's confusing before the reference to tree
inside the function shadows the outer variable with the same name. But due to how references work in JavaScript, it ends up modifying the outer variable anyway.
Here is what it does, step by step, considering only the first call:
tree
(that is {}
) and ["a", "b", "c"]
as arguments{}
{ a : {} }
tree.a
(which is empty){}
{ a : { b: {} } }
tree.a.b
(which is empty){}
{ a : { b: { c: {} } } }
tree.a.b.c
(which is empty)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With