Reputation: 8971
I have the following for
loop which is appending a rect
to a group
element:
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. However, when I remove the attr
chaining, it works as follows:
for(var i = 0; i < 5; i++) {
legend_group.append('rect');
}
Why is the for
loop not executing for each iteration?
Upvotes: 1
Views: 126
Reputation: 1216
That is because you add 10 to your increment counter in the first loop:
.attr('x', i += 10)
After that, in the first iteration, i
is 10, which is greater that your limit.
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
Upvotes: 0
Reputation: 16546
The for loop's second field is a condition that is checked before every loop run. Inside your loop you're adding 10 to i and assigning it at the same time. after the first run the loop logic sees that i is 10 and exits because the condition (i < 5) is not met anymore. Simply change i += 10
to i + 10
or i * 10
.
Upvotes: 1
Reputation: 25892
That is because in this line you are chainging i
itself to more than 5
.
.attr('x', i += 10)
You should have it, readonly like .attr('x', i + 10)
.
Upvotes: 3
Reputation: 154
Because you are adding +10 to i in this line .attr('x', i += 10).I guess you need something like i+10
Upvotes: 1