我在javascript中遇到了算法问题。基本上,我正在构建一个图表,我需要继续参考子图。问题是从一次迭代到另一次迭代,我放弃了这个引用,我仍然无法理解这种行为。这是我的代码。
<!DOCTYPE html>
<html>
<body>
<script>
const SIZE = 1000;
var graph = {
"name": "flare",
"children": [ ]
}
var testjson = {
"angular-chart.js@1.0.3": {
"chart.js@2.3.0": {
"chartjs-color@2.0.0": {
"chartjs-color-string@0.4.0": {
"color-name@1.1.1": {}
},
"color-convert@0.5.3": {}
},
"moment@2.15.2": {}
},
"angular@1.5.8": {}
}
};
function traverse_it(obj, myFunc){
var ref = graph;// .children;
for(var prop in obj){
if( !Object.keys(obj[prop]).length){
console.log("{}");
ref.push({'name': prop, 'size': SIZE });
return;
}
else if(typeof obj[prop]==='object'){
console.log("------------------------------");
console.log(typeof ref);
console.log('ref in the ginning of iteration');
console.log(ref);
ref = ref.children;
console.log(ref);
ref.push({'name': prop, 'children': [] });
console.log(ref);
ref = ref[ref.length -1];
console.log("--------graph----------------");
console.log(graph);
console.log("---------graph----------------");
console.log('ref at the end of iteration');
console.log(ref);
console.log("------------------------------");
if (graph.children.length > 1)
return;
traverse_it(obj[prop]);
}else{
console.log("error ");
throw err;
}
}
return;
}
traverse_it(testjson);
</script>
</body>
</html>
输出是这样的:
------------------------------
object
ref in the ginning of iteration
{
"name": "flare",
"children": []
}
[]
[
{
"name": "angular-chart.js@1.0.3",
"children": []
}
]
--------graph----------------
{
"name": "flare",
"children": [
{
"name": "angular-chart.js@1.0.3",
"children": []
}
]
}
---------graph----------------
ref at the end of iteration
{
"name": "angular-chart.js@1.0.3",
"children": []
}
------------------------------
------------------------------
object
ref in the ginning of iteration
{
"name": "flare",
"children": [
{
"name": "angular-chart.js@1.0.3",
"children": []
}
]
}
[
{
"name": "angular-chart.js@1.0.3",
"children": []
}
]
[
{
"name": "angular-chart.js@1.0.3",
"children": []
},
{
"name": "chart.js@2.3.0",
"children": []
}
]
--------graph----------------
{
"name": "flare",
"children": [
{
"name": "angular-chart.js@1.0.3",
"children": []
},
{
"name": "chart.js@2.3.0",
"children": []
}
]
}
---------graph----------------
ref at the end of iteration
{
"name": "chart.js@2.3.0",
"children": []
}
------------------------------
正如您在此输出中所看到的,ref正在从迭代1更改为2.如何在迭代结束时保持相同的ref(子图)值并开始新的迭代。