Working on a codecademy tutorial where I’m supposed to print out the “cells” of the table (the array within the array) like this
Cell Cell Cell
with two spaces between each cell. I’m assuming the result (for the first “row”) will look like
Person Age City
There should be no space at the end of the “row”.
I wrote the disastrous for loop below trying to follow the instructions from codecademy (copied below) but can’t get it to work. Can anyone give me a hand…
var table = [
["Person", "Age", "City"],
["Sue", 22, "San Francisco"],
["Joe", 45, "Halifax"]
];
for (var r in table) { ////// I wrote this for statement
var c;
var cells = table[r];
var rowText = "";
for(c = 0; c < cells; c++){
rowText += table[r][c];
if(c < cells - 1){ //only adds the space if not at end of line
rowText += " ";
}
}
console.log(rowText);
}
Instructions from Codecademy.com
We want to add another for loop and some formatting code so that we
can print out each of the three rows in the following format:Cell Cell Cell
There should be two spaces between each of the cell values, but not at
the end of a line. Each row should be on a separate line.In-depth instructions are in the exercise hint.
Remove the console.log statement in the body of the for loop. In the
body of the for loop, define a variable c. Also define a variable
named cells and set it equal to the length of the current row (which
can be found with table[r]). Define an empty string variable named
rowText. Make sure to set rowText is set to “”. Define another for
loop immediately after the variables from step 2.In the first loop parameter, set c equal to 0. In the second loop
parameter, make sure that the loop stops after c is one less than
cells. In the third loop parameter, increment c. In the body of the
loop from step 3, append the current cell (which can be found with
table[r][c]) to rowText. Use an if statement to also append two space
characters (this is ” “) to rowText if c is not the position of the
last cell in the row (this is true when c is less than cells – 1)
After the entire loop body from step 3, but inside of the loop body
from the last exercise, use console.log to print rowText.
use cells.length not cells I would think