2014-09-18 90 views
0

我有一些代碼需要打印下劃線,但對於它上面的行,我該怎麼做?我不確定如何將下劃線打印到上一行,對javascript沒有太多經驗。謝謝!JavaScript打印到上一行

var landscape = function() { 
    var result = ""; 
    var flat = function(size) { 
    for (var count = 0; count < size; count++) 
     result += "_"; 
    }; 
    var hill = function(size) { 
    result += " /"; 
    for (var count = 0; count < size; count++) 
     result += ""+ 
       "_"; 
    result += " \\"; 
    }; 


    //BUILD SCRIPT 
    flat(3) 
    hill(4); 
    flat(6); 
    hill(1); 
    flat(1); 
    //END SCRIPT 
    return result; 

it makes this ___ /____ \______ /_ \_`enter code here`enter code here` 
and i want this 
    _____ ___ 
___/  \__/ \____/\_ 

回答

2

您可以分別跟蹤兩行,然後在返回結果之前將它們連接起來。

JS:

function landscape() { 
    var resultTop = ''; 
    var resultBottom = ''; 

    function hill(size) { 
     resultTop += ' '; 
     resultBottom += '/'; 
     for (var i = 0; i < size; i++) { 
      resultTop += '_'; 
      resultBottom += ' '; 
     } 
     resultTop += ' '; 
     resultBottom += '\\'; 
    } 

    function flat(size) { 
     for (var i = 0; i < size; i++) { 
      resultTop += ' '; 
      resultBottom += '_'; 
     } 
    } 

    flat(3); 
    hill(4); 
    flat(6); 
    hill(1); 
    flat(1); 

    var result = resultTop + '<br/>' + resultBottom; 
    return result; 
} 

這裏有一個fiddle

1

一種解決方法是打印一個在頂部繪製一條線的unicode字符。原來有這樣的性格:Upper One-eighth Block

它在Unicode轉義"\u2594"&#9620;爲HTML實體,或者你可以簡單地複製/粘貼從下面的示例中的文字字符:

____/▔▔▔▔\____/▔▔\___