Leviathan_the_Great
Leviathan_the_Great

Reputation: 448

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. 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). that shouldn't effect it but I'm not sure as I'm new to TDD.

Upvotes: 0

Views: 52

Answers (2)

AJ Genung
AJ Genung

Reputation: 341

Your initializing I to be 300, and looping through while i < 300. That evaluates to false the first time the loop tries to run so the code in the for loop is ignored.

Upvotes: 0

Eddie D
Eddie D

Reputation: 1120

Your for loop condition is off. You set i = height / 2 and set the condition to i < height / 2. The condition is already false because (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)

Upvotes: 2

Related Questions