有人可以解释这段代码吗?我不知道“for”结构中的内容。
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": {}
}
}
}*/
答案 0 :(得分:1)
我已经扩展了for
循环的主体并添加了一些注释以尝试使事情更明确。
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];
}
答案 1 :(得分:1)
在函数内部对tree
的引用影响外部变量具有相同名称之前,这一点令人困惑。但由于引用如何在JavaScript中工作,它最终会修改外部变量。
这是它的作用,一步一步,只考虑第一个电话:
tree
(即{}
)和["a", "b", "c"]
作为参数{}
{ a : {} }
tree.a
(它是空的){}
{ a : { b: {} } }
tree.a.b
(它是空的){}
{ a : { b: { c: {} } } }
tree.a.b.c
(它是空的)