Javascript for循环控制台打印在一行

时间:2015-10-12 20:33:49

标签: javascript loops for-loop printing console

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

for(var i = 1; i < 11; i += 1) {
    console.log(i);
}

现在是

1
2
3
4
5
6
7
8
9
10

如何将输出全部放在一行(如下所示) 1 2 3 4 5 6 7 8 9 10)?

8 个答案:

答案 0 :(得分:18)

构建一个字符串,然后在循环后记录它。

&#13;
&#13;
var videoJsButtonClass = videojs.getComponent('Button');
var concreteButtonClass = videojs.extend(videoJsButtonClass, {

  // The `init()` method will also work for constructor logic here, but it is 
  // deprecated. If you provide an `init()` method, it will override the
  // `constructor()` method!
  constructor: function() {
    videoJsButtonClass.call(this, videojsInstance);
  }, // notice the comma

  handleClick: function(){
    // Do your stuff
  }
});

var concreteButtonInstance = videojsInstance.controlBar.addChild(new concreteButtonClass());
    concreteButtonInstance.addClass("vjs-" + name);
&#13;
&#13;
&#13;

答案 1 :(得分:2)

没问题,只需将它们连接成一行:

var result  = '';
for(var i = 1; i < 11; i += 1) {
  result = result + i;
}
console.log(result)

或更好,

console.log(Array.apply(null, {length: 10}).map(function(el, index){
   return index;
}).join(' '));

继续前进并学习东西! 祝你好运!

答案 2 :(得分:1)

或者,要在单行中打印,您可以在 Javascript 中使用 repeat-

for(let j = 0; j < 5; j++){
    console.log('*'.repeat(j))    
}

答案 3 :(得分:0)

可以有另一种方法在单行中打印计数器,console.log()在没有指定的情况下放置尾随换行符,我们不能省略它。

&#13;
&#13;
let str = '',i=1;
while(i<=10){
    str += i+'';
    i += 1;
}

console.log(str);
&#13;
&#13;
&#13;

答案 4 :(得分:0)

// 1 to n
const n = 10;

// create new array with numbers 0 to n
// remove skip first element (0) using splice
// join all the numbers (separated by space)
const stringOfNumbers = [...Array(n+1).keys()].splice(1).join(' ');

// output the result
console.log(stringOfNumbers);

答案 5 :(得分:0)

在Node.js中,您还可以使用以下命令:

process.stdout.write()

这将使您避免将填充变量添加到范围中,而仅打印for循环中的每个项目。

答案 6 :(得分:0)

let n=0;

for ( i = 1; i <= 10; i++)
    {
      n += i + “ “;
      console.log(n);
}

答案 7 :(得分:0)

// we can use process.stdout.write() method to print to console 
// without trailing newline.

// It only takes strings as arguments. 
// But in this case (i + " ") is a string so it works.

for(var i = 1; i < 11; i += 1) 
{
    process.stdout.write(i + " ");
}

//Output :- 1 2 3 4 5 6 7 8 9 10


//NOTE - It will Work with Node.js