For-loop不会循环遍历图形数据

时间:2017-01-30 00:55:11

标签: javascript arrays for-loop graph

我想编辑图表,以便显示我的两个数组的结果。 我要编辑的代码位于:http://jsfiddle.net/mahbub/2Dv3E/

我用自己的for循环替换了var links

var z;
var cars = ["Saab", "Volvo", "BMW"]; 
var person = ["David", "Joe", "Harry"];

for(z=0;z<5;z++){
var links = [
{
    source: cars[z],
    target: person[z]
}];
}

我想要的输出是来创建一个图表,其中Saab链接到David,Volvo链接到Joe和BMW链接到Harry

问题是我的for循环没有循环var links因此它只输出一个链接,而不是3.

3 个答案:

答案 0 :(得分:1)

我认为您应该创建一个对象,然后将其推送到链接:

var cars = ["Saab", "Volvo", "BMW"]; 
var person = ["David", "Joe", "Harry"];
var links = [];
for(var z = 0; z < cars.length; z++){
 links.push({source: cars[z],
             target: person[z]
 });
}

答案 1 :(得分:0)

您需要将每个项目推送到链接数组,如下所示:

    var z;
    var cars = ["Saab", "Volvo", "BMW"]; 
    var person = ["David", "Joe", "Harry"];
    var links = [{
        source: "2335656544544",
        target: "2335656544589"
    }, {
        source: "2335656544544",
        target: "2335656544590"
    }, {
        source: "2335656544544",
        target: "2335656544591"
    }];

for(z = 0; z < 5; z++){
    links.push({
        source: cars[z],
        target: person[z]
    });
}

答案 2 :(得分:0)

问题:

对于循环的每次迭代,您都是:

  • 声明变量link
  • link的值赋给包含对象的数组。 您没有添加到阵列。。您正使用当前对象覆盖任何先前的值
  • 你最终得到一个名为link的变量,其值是在循环的_last_迭代中设置的对象

建议的解决方案:

使用Array.prototype.push将项添加到已在for循环之外声明和实例化的数组中:

// declare links outside of for loop and before it
// initialise is value to an empty array
var links = [];

// The condition this loop will stop will be
// the length of the cars array
// This should avoid creating unwanted values in your links array
// by stopping array for the number of elements
// present in the cars array
for(z=0; z<cars.length; z++){

  // "push" your object into links array
  // for each iteration of the loop
  links.push({
               source: cars[z],
               target: person[z]
            });
}