javascript使用for循环创建编号的行

时间:2017-09-28 20:55:15

标签: javascript for-loop

到目前为止,这是我的代码:

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

2 个答案:

答案 0 :(得分:2)

只需使用三元运算符检查N - col的值是否等于循环内row - 1的值,如下所示:

&#13;
&#13;
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;
&#13;
&#13;

在旁注中,编号0开始,而不是1,以使代码稍微复杂一点。我的建议是重构它看起来像这样:

&#13;
&#13;
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;
&#13;
&#13;

答案 1 :(得分:0)

所有你要做的就是检查你是否在正确的位置。行变量将跟踪实际数字。

&#13;
&#13;
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;
&#13;
&#13;

我做了N + 1,因为你开始在索引1处进行迭代