【问题标题】:How can I assign values to an array in D3 using a loop?如何使用循环将值分配给 D3 中的数组?
【发布时间】:2023-03-23 08:17:01
【问题描述】:

在下面的代码中,我希望为变量 arr 赋值。目前我是通过引用点数组的每个索引来手动完成的。有没有办法通过使用 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);

【问题讨论】:

    标签: javascript arrays d3.js


    【解决方案1】:

    如果需要,您可以执行 for 循环,并且可以使用数组的长度来设置循环的限制。我不确定你在 points 里面有什么,但你可以这样做:

    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'})
    }
    

    【讨论】:

      【解决方案2】:

      看看你的例子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'});
      }
      

      不过,我不太确定 ' 350 A 10 10 0 1 0 ' 中的第四个值是从哪里得到的。
      我还假设在第一个 points[] 中,您想要 scren 的内容,因为它们似乎匹配。

      无论如何,这应该让您了解如何填充数组。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-05
        • 1970-01-01
        • 2017-11-18
        • 2018-11-04
        相关资源
        最近更新 更多