CodeHS 8.14.4:Summing Grid问题求助——JavaScript函数异常排查
Fix JavaScript sumGrid Function to Calculate Row+Column Index Sum Correctly
The Problem
You need a sumGrid(grid) function that fills each grid position with the sum of its row index and column index, then outputs the values in order. For a Grid(2, 3) (2 rows, 3 columns), the expected output is 0 1 2 1 2 3, but your current code outputs 0 1 2 1 2 undefined.
What's Wrong With Your Current Code
Let's break down the issues in your sumGrid function:
- You’re modifying the outer loop’s
rowvariable inside the inner loop (row += 1), which completely breaks the loop’s iteration logic. - You’ve added two separate nested loops that don’t work together—you’re first printing row indices, then trying to print column indices, instead of calculating their sum directly.
- You’re re-declaring
rowinside the second loop, causing scope confusion, and yourcolinitialization is incorrect, leading to theundefinedvalue at the end. - Most importantly: you never actually calculate the sum of the row and column indices anywhere in your code!
Fixed Code
Here's the corrected version of the sumGrid function that meets your requirements:
function start(){ var grid = new Grid(2, 3); println(sumGrid(grid)); } function sumGrid(grid){ // Create an array to collect all sum values for clean formatting var result = []; // Loop through each row index for(var row = 0; row < grid.numRows(); row++){ // Loop through each column index in the current row for(var col = 0; col < grid.numCols(); col++){ // Calculate the sum of row and column index var cellSum = row + col; // Add the sum to our result array result.push(cellSum); } } // Convert the array to a space-separated string and return it return result.join(" "); }
How This Works
- Result Collection: Using an array to store sums ensures we avoid extra trailing spaces or messy newlines in the final output.
- Consistent Loops: The outer loop handles row indices, and the inner loop handles column indices—no modification of loop variables inside the loops, so iteration stays predictable.
- Direct Sum Calculation: For every cell, we compute
row + colexactly as the problem requires. - Clean Formatting:
join(" ")converts the array into a neat space-separated string that matches the expected output.
Alternative: Direct Printing (If You Don't Need to Return the String)
If you prefer to print directly instead of returning a formatted string, you can adjust the function like this:
function sumGrid(grid){ var output = ""; for(var row = 0; row < grid.numRows(); row++){ for(var col = 0; col < grid.numCols(); col++){ output += (row + col) + " "; } } // Trim the trailing space before printing println(output.trim()); }
This will print the exact expected output: 0 1 2 1 2 3
内容的提问来源于stack exchange,提问作者Sophia Simpson
相关产品推荐
相关产品推荐

