0

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.

2
  • let i = canvas.height / 2; i < canvas.height If i is initialized to be equal to canvas.height, then it will never be < than canvas.height. Commented May 31, 2018 at 2:21
  • You are initializing i in the loop as canvas.height / 2, which doesn't meet the condition i < canvas.height / 2. Nothing in the body of the for loop is executed, so slopeValues will be the empty array. Commented May 31, 2018 at 2:21

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.