2017-04-20 45 views
-4

我想從符號「#」輸出樓梯。它應該是這樣的:從符號創建樓梯

enter image description here

但我做到的是:

enter image description here

我應該怎麼做才能正確的輸出?

var n = 6; 
var rows=[]; 
var cols=[]; 

for(i=n-1;i>=0;i--) { 
    rows=[]; 
    for(j=0;j<n;j++) { 
     if(j >= i) { 
      rows[j] = "#"; 
     } else { 
      rows[j] = ""; 
     } 
    } 

    cols.push(rows); 
    cols.splice(0, cols.length - 1); 
    console.log(cols.join(",")); 
} 
+1

什麼困惑嗎?您明確要求它加入的逗號,或者在插入空字符串而不是空格時缺少空格? –

+0

@RowlandShaw我想再次加入數組「cols」的元素以刪除逗號,但由於錯誤,我不能。我的目標是通過一項任務,但編譯器告訴我答案是錯誤的。這裏是scrshot:[鏈接](http://ef-englishfirst.ru/i/output.jpg) – IndigoHollow

回答

0

把它想象成一個座標系,循環遍歷y和x並添加所需的符號。

請記住,如果您希望雙面打印,請使用當前y增加最大x。

function ladder(size, dualSided, empty, occupied) { 
 
    if (dualSided === void 0) { dualSided = true; } 
 
    if (empty === void 0) { empty = " "; } 
 
    if (occupied === void 0) { occupied = "▲"; } 
 
    var str = ""; 
 
    for (var y = 0; y < size; y++) { 
 
     for (var x = 0; x < size + y; x++) { 
 
      if (dualSided != true && x == size) { 
 
       break; 
 
      } 
 
      if (x >= size - y - 1) { 
 
       str += occupied; 
 
      } 
 
      else { 
 
       str += empty; 
 
      } 
 
     } 
 
     str += "\n"; 
 
    } 
 
    return str; 
 
} 
 
console.log(ladder(20, false));

+0

謝謝!這工作正常! – IndigoHollow

0

好吧,試試這個(最後3行);

cols.push(rows.join("")); 
cols.splice(0, cols.length - 1); 
console.log(cols.join("")); 

問題是你正在推陣列(行)在列中,其中行數組本身包含逗號。如果你做cols.push(rows.join(「」)),所有的逗號將被刪除。

+0

謝謝!但輸出是顛倒的:[鏈接](http://ef-englishfirst.ru/i/outpu1.jpg) cols.reverse()沒有幫助。 – IndigoHollow