[英]for loop executing only for first iteration
I have the following for
loop which is appending a rect
to a group
element: 我有以下
for
循环,它将rect
附加到group
元素:
var svg_container = d3.select(element[0]).append('svg')
.attr('width', width)
.attr('height', 50)
var legend_group = svg_container.append('g');
for(var i = 0; i < 5; i++) {
legend_group.append('rect')
.attr('x', i += 10)
.attr('y', 5)
.attr('width', 10)
.attr('height', 5)
.attr('fill', 'red')
}
But it is running only for i = 0
and there are no errors. 但是它仅在
i = 0
运行,并且没有错误。 However, when I remove the attr
chaining, it works as follows: 但是,当我删除
attr
链时,它的工作方式如下:
for(var i = 0; i < 5; i++) {
legend_group.append('rect');
}
Why is the for
loop not executing for each iteration? 为什么
for
循环没有为每个迭代执行?
That is because in this line you are chainging i
itself to more than 5
. 这是因为在这一行中,您将
i
自身链接到5
。
.attr('x', i += 10)
You should have it, readonly like .attr('x', i + 10)
. 您应该像只读的
.attr('x', i + 10)
一样拥有它。
因为您在这一行.attr('x',i + = 10)中向i添加+10我想您需要像i + 10这样的东西
The for loop's second field is a condition that is checked before every loop run. for循环的第二个字段是在每次循环运行之前检查的条件。 Inside your loop you're adding 10 to i and assigning it at the same time.
在循环内,您要向i添加10并同时分配它。 after the first run the loop logic sees that i is 10 and exits because the condition (i < 5) is not met anymore.
第一次运行后,循环逻辑将看到i为10并退出,因为不再满足条件(i <5)。 Simply change
i += 10
to i + 10
or i * 10
. 只需将
i += 10
更改为i + 10
或i * 10
。
That is because you add 10 to your increment counter in the first loop: 那是因为您在第一个循环中将10加到增量计数器中:
.attr('x', i += 10)
After that, in the first iteration, i
is 10, which is greater that your limit. 之后,在第一次迭代中,
i
为10,这比您的限制大。
Most likely you are using the same variable by mistake, but there is not enough information here. 您很可能错误地使用了相同的变量,但是这里没有足够的信息。 But if you do, change the
i
inside your loop, or the i
in the for
loop conditions 但是,如果你这样做,改变
i
你的循环内,或者i
在for
循环条件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.