所以我的目标是在控制台中打印乘法口诀表。这段代码有效,但只有在我尝试将其放入函数中时才会有效。
我已将循环末尾的 console.log 替换为返回(见下文),然后它只给我 3 行输出。我希望这是足够清楚的,这是我第一次发帖。
const multiplicationTable = function(maxValue) {
for (let i = 0; i < 0; i++){
// This is shown to verify which value is the one on the
multiplication table with each line
//console.log(""+i);
// then it clears the variable tableLine with each new line
let tableLine = "";
for (let j = 1; j <= maxValue; j++) {
// It will add the results to a string each time
tableLine += ""+(i*j)+" ";
} return tableLine; //and display each line in the console
}
}
console.log(multiplicationTable(1));
console.log(multiplicationTable(5));
console.log(multiplicationTable(10));
//1
//
//1 2 3 4 5
//2 4 6 8 10
//3 6 9 12 15
//4 8 12 16 20
//5 10 15 20 25
//
//1 2 3 4 5 6 7 8 9 10
//2 4 6 8 10 12 14 16 18 20
//3 6 9 12 15 18 21 24 27 30
//4 8 12 16 20 24 28 32 36 40
//5 10 15 20 25 30 35 40 45 50
//6 12 18 24 30 36 42 48 54 60
//7 14 21 28 35 42 49 56 63 70
//8 16 24 32 40 48 56 64 72 80
//9 18 27 36 45 54 63 72 81 90
//10 20 30 40 50 60 70 80 90 100
最佳答案
当您在函数内部使用return
时,它会立即退出该函数并且不会继续其余的处理。
您需要做的是使用另一个常量(例如table
)来存储您的tableLine
。在处理结束时,您返回 table
值。
我已经修改了你的代码,你可以在下面看到它以供引用。 您将能够获得与预期相同的输出。
function multiplicationTable(maxValue) {
let table = "";
for (let i = 1; i <= maxValue; i++) {
let tableLine = "";
for (let j = 1; j <= maxValue; j++) {
tableLine += ""+(i*j)+" ";
}
tableLine += "\n";
table += tableLine;
}
return table;
}
关于javascript - 乘法表打印到控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57796676/