到目前为止,这是我的代码:
let N = +prompt("Enter a number: ");
let result = "";
for (let row=1; row <= N; row++){
for (let col=1; col <= N; col++){
result +=".";
}
result +="\n";
}
console.log(result);
目前,它仅根据用户的输入打印一盒点。 如何使其打印如下?
....1
...2.
..3..
.4...
5....
答案 0 :(得分:2)
只需使用三元运算符检查N - col
的值是否等于循环内row - 1
的值,如下所示:
let N = +prompt("Enter a number: ");
let result = "";
for (let row = 1; row <= N; row++) {
for (let col = 1; col <= N; col++) {
result += N - col === row - 1 ? row : ".";
}
result += "\n";
}
console.log(result);
&#13;
在旁注中,编号应从0
开始,而不是1
,以使代码稍微复杂一点。我的建议是重构它看起来像这样:
let N = +prompt("Enter a number: ");
let result = "";
for (let row = 0; row < N; row++) {
for (let col = 0; col < N; col++) {
result += N - col - 1 === row ? row + 1 : ".";
}
result += "\n";
}
console.log(result);
&#13;
答案 1 :(得分:0)
所有你要做的就是检查你是否在正确的位置。行变量将跟踪实际数字。
let N = +prompt("Enter a number: ");
let result = "";
for (let row=1; row <= N; row++){
for (let col=1; col <= N; col++){
if(col == (N +1 -row)){
result +=row;
}
else{
result +=".";
}
}
result +="\n";
}
console.log(result);
&#13;
我做了N + 1,因为你开始在索引1处进行迭代