You're using a single array levelAndPath
, and pushing references to it into levelInfo
, as opposed to pushing different arrays.(您正在使用单个数组levelAndPath
,并将对它的引用推送到levelInfo
,而不是推送不同的数组。)
(I haven't looked if there are any other errors beyond that, but this one is easily fixable by moving var levelAndPath=[];
inside forEach
.)((我没有查看是否有其他错误,但是可以通过在forEach
内移动var levelAndPath=[];
来轻松解决此错误。))
It is not about closures.(它与闭包无关。) It is the fact that levelInfo[parent]=levelAndPath;
(实际上是levelInfo[parent]=levelAndPath;
) doesn't copy levelAndPath
- it just sticks in a reference.(不复制levelAndPath
只是levelAndPath
在参考中。) Here's a snazzy demo, thanks to the advances in Stack Overflow snippets:(这是一个令人眼花demo乱的演示,这要归功于Stack Overflow片段的进步:)
let a = [1, 2, 3]; let b = [a, a, a]; a[2] = 4; console.log(JSON.stringify(b)); // Huh? [[1,2,4],[1,2,4],[1,2,4]]?!? console.log(b); // Here's what _really_ happened...
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…