2017-04-20 44 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