我如何一遍又一遍地遍历一个数组,同时将它的每个值分配给我 DOM 中的所有 svg

How can I iterate through an array over and over again while assigning each of its values to all the svgs in my DOM

抱歉,如果我的问题措辞不当。我是初学者,不知道事物的正确标签。

我正在使用 d3.js 制作日本地图,并想为每个都道府县分配一种颜色。每个县都有自己的 svg。我有一个我想使用的颜色的十六进制值数组,基本上想写一个函数,将数组的第一种颜色分配给第一个 svg 的 "fill" 属性,第二个到第二个等等。由于都道府县太多,颜色有时不得不重复。我真的很难构思如何解决这个问题,希望得到任何帮助!我的代码如下。我认为代码应该放在 javascript 的底部,我有 ?评论。

此外,如果有帮助,其基础来自 Mike Bostock 的 "let's make a map" 教程。

<!DOCTYPE html>
<head>
<meta charset="utf-8">
<style>



</style>
</head>
<body>
<script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="//d3js.org/topojson.v1.min.js"></script>
<script>

var width = 960;
var height = 1160;

/* list of colors to iterate thru for prefecture color */
var colors = ["#8dd3c7", "#ffffb3", "#bebada", "#fb8072", "#80b1d3",
              "#fdb462", "#b3de69", "#fccde5", "#d9d9d9"];

var projection = d3.geo.mercator()
    .center([138.3, 39.2])
    .scale(1500);

var path = d3.geo.path()
    .projection(projection);

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

/* draws the map. try to make a loop in here which uses the data id of
    the prefectures to uses the color list above to differentiate pref*/
d3.json("japanv2.json", function(error, japan) {
  svg.selectAll(".prefecture")
      .data(topojson.feature(japan, japan.objects.prefectures).features)
    .enter().append("path")
      .attr("class", function (d) { return "prefecture " + d.id; })
      .attr("d", path)
/*?*/ .attr("fill", 
      }
});


</script>
</body>
</html>

我以前从未使用过 D3,但跟踪您在数组中的位置还不错。

我首先会使用另一个变量跟踪您在数组中的位置,可能设置在 var colors 行下。

var currentColor = 0;

那么当你改变县的颜色时,你可以使用以下方法引用数组中的当前位置:

colors[currentColor]

完成后,您需要更新您的 currentColor:

currentColor++;
if (currentColor == colors.length) {
    currentColor = 0;
}

这会将 currentColor 值递增 +1,然后在使用最后一种颜色后将其重置回 0。这样,如果你有更多的县,你可以使用从头开始的颜色。

更新

仔细查看您的代码,我认为我在回答中提到的 colors[currentColor] 应该放在这一行的逗号之后:

/*?*/ .attr("fill", 

将其放入属性中:

.attr("fill", function(d,i){
    return colors[i%colors.length]
});

这段代码有什么作用?

首先,function(d,i) return 中的 i 是您的每个路径的索引。所以,如果你这样做:

.attr("fill", function(d,i){
    console.log(i);
    return colors[i%colors.length];
});

您会在控制台上看到一堆数字。如果你有,比方说,200 条路径,i 从 0 到 199。

现在模运算符:

x % y

是return部门的remainder。因此,鉴于您的 colors 是一个包含 9 种颜色的数组,因此:

i % colors.length

请问return这个序列:

0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 1 etc

您可以用来获取 colors 值。

PS:在地图中,任何一张地图,我们只需要4 colours就可以避免任意两个颜色相同的区域有共同的边界! (难以置信,我知道...)