JavaScript中for循环推对象入数组得空数组问题求助(斜率计算)
Hey there! Let's walk through what's causing your empty array and how to fix it, plus touch on your Mocha/TDD question.
The Immediate Problem: Your Loop Condition
The root cause of your empty slopeValues array is a broken loop condition. Let's break down your loop line:
for (let i = canvas.height / 2; i < canvas.height / 2; i--) {
- You initialize
ito300(sincecanvas.height / 2 = 600 / 2 = 300) - The loop condition checks if
i < 300—which is false right from the start. So the loop body never runs at all, hence the empty array.
Fixing the Loop + Calculating Slope 1/2 Points
First, let's fix the loop to actually execute. Then we'll add logic to generate points with a slope of 1/2.
Slope 1/2 means for every 1 unit you move down (or up) on the y-axis, you move 2 units right (or left) on the x-axis. Let's assume you want points starting from the middle of the canvas (y = 300) and moving down to the bottom, calculating the corresponding x values:
const canvas = { width: 1200, height: 600 }; const slopeValues = []; const slope = 1/2; // Start at the middle y-value, loop down to y=0 for (let y = canvas.height / 2; y >= 0; y--) { // Calculate x based on slope: Δx = Δy / slope. Since we're moving down, Δy = 300 - y const x = (canvas.height / 2 - y) / slope; // Only add points that fit within the canvas width if (x <= canvas.width) { slopeValues.push({ x, y }); } } console.log(slopeValues); // Now this will have populated points!
Alternatively, if you want to iterate over x-values and calculate corresponding y-values (ensuring they stay within the canvas):
const canvas = { width: 1200, height: 600 }; const slopeValues = []; const slope = 1/2; const startingY = canvas.height / 2; // Y-intercept at the canvas middle for (let x = 0; x <= canvas.width; x++) { const y = slope * x + startingY; // Keep points within the canvas height bounds if (y >= 0 && y <= canvas.height) { slopeValues.push({ x, y }); } } console.log(slopeValues);
Mocha/TDD Context
Your empty array issue isn't related to Mocha or TDD itself. The loop logic error would happen in any JavaScript environment. That said, when writing tests:
- Make sure you're initializing variables like
canvasconsistently in your test cases - Write assertions that check for the expected number of points, or specific point values (e.g.,
expect(slopeValues.length).to.be.greaterThan(0)orexpect(slopeValues[0]).to.deep.equal({ x: 0, y: 300 }))
内容的提问来源于stack exchange,提问作者Leviathan_the_Great

