select 和更改 d3 中的圆圈颜色的更清洁和更好的方法

Cleaner and better way to select and change colour of circles in d3

经过大量尝试后,我设法使以下函数同时更改所有 7 个圆圈的颜色。有一个变量颜色,它是一个颜色字符串数组。

这是我的函数:

function colorSquares(){
    for(let i = 0; i<7 ; i++){
        let id = '#s' + i ;
        d3.select(id).attr('fill',colors[i]);
     }
}

我忍不住认为有一种更简单的方法可以做到这一点!我这样创建了 7 个圆圈:

for(let i = 0 ; i< 7; i++){
    const circle = d3.select('.canvas')
        .append('circle')
            .attr('cx', 70 + i* 50)
            .attr('cy', 100)
            .attr('r', 20)
            .attr('stroke' ,'grey')
            .attr('stroke-width', 5)
            .attr('id' , 'c'+i );

}

如您所见,我手动制作了一个字符串,并使用 .attr 将其添加到每个圆圈中,然后弄乱了字符串以稍后调用该圆圈。有没有人有更干净更好的方法来做到这一点,实际上我正在寻找更好的方法来创建然后 select 圈子这样我就不必将字符串作为 ID

尝试

d3.select('.canvas')
  .selectAll('circle')
  .attr('fill', (d, i) => colors[i]);