简体   繁体   English

for循环仅在第一次迭代时执行

[英]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 + 10i * 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你的循环内,或者ifor循环条件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM