简体   繁体   中英

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. 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.

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. I'm not sure about what do you have inside points but you could do something like:

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:

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.
I also assumed that in the first points[] , you wanted the contents of scren , since those seemed to match.

Any way, this should give you an idea on how to fill the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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