【问题标题】:JavaScript: Is there any way to print outputs without newline?JavaScript:有没有办法在没有换行符的情况下打印输出?
【发布时间】:2018-12-16 18:50:40
【问题描述】:

我正在学习 JavaScript,我正在尝试打印这个特定的哈希序列:

#
##
###

我写了这段代码来产生序列:

for(let i = 0; i < 3; i++){
    for(let j = 0; j <= i; j++){
        print('#');
    }
    print('\n');
}

注意:我正在使用 rhino 在我的 Ubuntu 终端上执行程序。

rhino <filename>.js              //Command used to execute JavaScript file.

我得到的输出:

#


#
#


#
#
#

我用这个程序得到了正确的输出:

var starString = "";
for(let i = 0; i < 3; i++){
    for(let j = 0; j <= i; j++){
        starString += '#';
    }
    print(starString);
    starString = "";
}

我的问题是:是否有一个我可以使用的打印语句不在语句末尾添加换行符?

【问题讨论】:

    标签: javascript rhino


    【解决方案1】:
    console.log('Node js - hello world');
    for(var counter = 0; counter< 5 ;counter++){
        // console.log("----------------");
        var pound = "#";
        for(var localcounter = 0; localcounter < counter; localcounter++ ){
    
          //console.log("localcounter is ", localcounter);
           //console.log("counter is ", counter);
          //console.log(pound);
          pound += "#";
          //console.log(pound);
        }
        console.log(pound);
        //console.log("----------------");
    
        //
        pound = "";
        pound = null;
    }
    

    【讨论】:

      【解决方案2】:

      不,不直接使用print()。但是,您可以使用 System.out.print() 制作自己的函数,该函数在没有新行的情况下打印:

      function printNOn(arg) {
           java.lang.System.out.print(arg)
      }
      

      结果:

      MBP:rhino1_7R4 mark$ java -jar js.jar
      Rhino 1.7 release 4 2012 06 18
      js> function printNOn(arg) {
           java.lang.System.out.print(arg)
      } 
      js> for(let i = 0; i < 3; i++){
        >     for(let j = 0; j <= i; j++){
        >         printNOn("#")
        >     }
        >     printNOn('\n')
        > }
      #
      ##
      ###
      js>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-04
        相关资源
        最近更新 更多