gpt4 book ai didi

javascript - 使用 for 循环访问嵌套数组的单元格

转载 作者:行者123 更新时间:2023-12-02 05:05:30 25 4
gpt4 key购买 nike

正在编写一个 codecademy 教程,我应该像这样打印出表格的“单元格”(数组中的数组)

Cell Cell Cell

每个单元格之间有两个空格。我假设结果(第一个“行”)看起来像

Person  Age  City

“行”的末尾不应有空格。

我在下面写了一个灾难性的 for 循环,试图按照 codecademy 的说明(复制在下面)但无法让它工作。谁能帮帮我...

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);

}

来自 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.

最佳答案

使用 cells.length 而不是我认为的单元格

关于javascript - 使用 for 循环访问嵌套数组的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12184491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com