我试图从我的for循环输出到控制台中的单行打印

时间:2017-11-26 17:46:40

标签: javascript loops for-loop printing console

var n = Number(Math.ceil(Math.random()*10));
console.log(n);
var newN= n-1;  
var counter = 1;

while(counter <=  n){  
    for (i = 1; i <= n; i++){
     console.log(newN);
    }
    
    newN+=2;
    counter++;
}

它必须如下所示:

enter image description here

3 个答案:

答案 0 :(得分:0)

为每一行构建一个字符串,然后在完成时console.log

var s = '';

for (i = 1; i <= n; i++){
  s += newN + '\t';
}

console.log(s);

答案 1 :(得分:0)

console.log总是换行,所以创建一个字符串并用数字连续N次,然后像这样打印:

var n = Number(Math.ceil(Math.random()*10));
console.log(n);
var newN= n-1;  
var counter = 1;

while(counter <=  n){  
  let str = ''
  for (i = 1; i <= n; i++){
   str = str + newN
  }
  console.log(str)

  newN+=2;
  counter++;
}

答案 2 :(得分:0)

var n = Math.ceil(Math.random()*10);
console.log(n);

for(let count = 1; count < n; count++)
   console.log(("" + (n - 1 + count * 2)).repeat(n));

您只需使用重复连续打印 n 次。