简体   繁体   English

将对象推入数组以进行循环

[英]pushing objects to array in for loop

so i have a problem with some seemingly simple code. 所以我对一些看似简单的代码有疑问。 i am trying to calculate the points on a slope of 1/2. 我正在尝试计算1/2斜率上的点。 but all I am getting is the empty array object. 但是我得到的只是空数组对象。

 const canvas = { width: 1200, height: 600 }; const slopeValues = []; for (let i = canvas.height / 2; i < canvas.height / 2; i--) { let obj = {}; obj.x = i; slopeValues.push(obj); } console.log(slopeValues) 

I should also mention that I do have the original code structured in a test suite(mocha). 我还应该提到,我确实在测试套件(mocha)中构建了原始代码。 that shouldn't effect it but I'm not sure as I'm new to TDD. 那不会影响它,但是我不确定,因为我是TDD的新手。

Your for loop condition is off. 您的for循环条件已关闭。 You set i = height / 2 and set the condition to i < height / 2 . 设置i = height / 2并将条件设置为i < height / 2 The condition is already false because (i == height / 2) != (i < height) 该条件已经为假,因为(i == height / 2) != (i < height)

Try this one instead: 尝试以下一项:

 const canvas = { width: 1200, height: 600 }; const slopeValues = []; for (let i = canvas.height / 2; i >= 0 / 2; i--) { let obj = {}; obj.x = i; slopeValues.push(obj); } console.log(slopeValues) 

您将i初始化为300,然后在i <300时循环通过。第一次尝试运行该循环时,结果为false,因此将忽略for循环中的代码。

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

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