简体   繁体   English

如何使用循环将值分配给D3中的数组?

[英]How can I assign values to an array in D3 using a loop?

In the following code I wish to assign values to the variable arr. 在下面的代码中,我希望将值分配给变量arr。 Currently I am doing it manually by referring to each index of points array. 目前,我正在通过引用点数组的每个索引来手动执行此操作。 Is there a way to to do it in a single step , by using a for loop or something similar. 有没有一种方法可以通过使用for循环或类似方法一步完成。

var svg = d3.select("body")
    .append("svg")
        .attr("width", 2000)
        .attr("height", 2000);

var scren = [1, 2, 3, 1, 4, 5, 6, 4];
var maximum =d3.max(scren);

var points = d3.range(1, maximum).map(function(i) {
    return [i * 2000 / (maximum), 350];
});     

var arr = [
    {d: 'M ' + points[1][0] +' 350 A 10 10 0 1 0 '+ points[0][0]+' 350', stroke: 'green', 'strokewidth': 2, fill: 'none'},
    {d: 'M ' + points[2][0] +' 350 A 10 5 0 1 0 ' + points[1][0]+' 350', stroke: 'green', 'strokewidth': 2, fill: 'none'},
    // etc..
];

svg.selectAll('path')
    .data(arr)
    .enter()
    .append('path')
    .attr('d', function(d) {return d.d;})
    .attr('stroke', function(d) {return d.stroke;})
    .attr('stroke-width', function(d) {return d.strokewidth;})
    .attr('fill', function(d) {return d.fill;});

svg.selectAll("circle")
    .data(points)
    .enter()
    .append("circle")
    .attr("cx", function(d) {
        return d[0];
    })
    .attr("cy", function(d) {
        return d[1];
    })
    .attr("r", 5);

You can do a for loop if you need, and you can use the length of your array to set the limits of the loop. 如果需要,可以执行for循环,也可以使用数组的长度设置循环的限制。 I'm not sure about what do you have inside points but you could do something like: 我不确定您的内在points是什么,但是您可以执行以下操作:

var arr = []; var arr = [];

for (i = 0; i < points.length - 1; i++) { 
    arr.push({d: 'M ' + points[i+1][0] +' 350 A 10 5 0 1 0 ' + points[i][0]+' 350', stroke: 'green', 'strokewidth': 2, fill: 'none'})
}

Looking at the example arr you have, this should work: 查看您有的示例arr ,这应该可以工作:

var arr = [];

for(var i = 0; i < points.length; i++){
    arr.push({d: 'M ' + points[scren[i]][0] +' 350 A 10 10 0 1 0 '+ points[i][0]+' 350',
        stroke: 'green', 'strokewidth': 2, fill: 'none'});
}

I'm not quite sure where you got the 4th value in ' 350 A 10 10 0 1 0 ' from, though. 不过,我不太确定您从何处获得了' 350 A 10 10 0 1 0 '的第4个值。
I also assumed that in the first points[] , you wanted the contents of scren , since those seemed to match. 我还假定在第一个points[] ,您需要scren的内容,因为这些内容似乎匹配。

Any way, this should give you an idea on how to fill the array. 无论如何,这应该使您了解如何填充数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM