gpt4 book ai didi

javascript - 将数组转换为树

转载 作者:数据小太阳 更新时间:2023-10-29 05:33:53 26 4
gpt4 key购买 nike

有人可以解释这段代码吗?我不明白“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": {}
}
}
}*/

最佳答案

我扩展了 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];
}

关于javascript - 将数组转换为树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14507676/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com