在Javascript中,如何并排打印2个图表?

时间:2017-11-22 22:03:33

标签: javascript function methods diagrams

我在Practice.it上做了一个JavaScript练习题,并且有一个问题就是并排打印2个火箭船。

我已经打印过一张,但我无法弄清楚如何在第一艘旁边打印另一艘火箭飞船。

另外,有没有办法使用for循环?

function rocket(){
  triangle();
  line();
  sides();
  line();
  console.log("|Rocket |");
  console.log("|  #1   |");
  line();
  sides();
  line();
  triangle(); 
}

function triangle(){
  console.log("   / \\");
  console.log("  /   \\");
  console.log(" /     \\");
}

function line(){
  console.log("+-------+");
}

function sides(){
  console.log("|       |");
}

rocket();

输出:

   / \
  /   \
 /     \
+-------+
|       |
+-------+
|Rocket |
|  #2   |
+-------+
|       |
+-------+
   / \
  /   \
 /     \

3 个答案:

答案 0 :(得分:1)

不应在函数中正确记录,而应将图表字符串放在数组中。

例如:

function triangle(){
  return 
  ["   / \\", 
  "  /   \\",
  " /     \\"]
}

这样,如果你想要并排打印两个,你只需要创建一个接收图表的函数,以及用于水平分隔它们的空间量。该函数将逐行打印图表(索引由数组索引)。

例如:

function printDiagrams(diagramList /* This is an array of arrays */, spacing) {
  // Get the size of the biggest array in diagramList
  var size= biggestDiagramSize(diagramList )
  // Here, you iterate in the diagrams array line by line and print
  for(i = 0, i < size, i++ ) {
    // Iterate over diagramList and print its lines
    // Careful not to exceed arrays bound.
    // Ex: console.log(diagram1[i] + spacing + diagram2[i] + spacing + diagramN[i])
  }

}

您还需要一个函数来组合图表。它只接收数组并返回它们的串联。

注意:即使您并排打印不同的图表,也能正常工作。

答案 1 :(得分:1)

快速而肮脏的方法就是将每个字符串与自身连接起来。因此对于console.log("+--------+")的每个实例都使用:

console.log("+--------+".repeat(2));

只需为每个字符串执行此操作。

答案 2 :(得分:0)

您可以为rocket函数定义参数,在函数中使用String.prototype.repeat()String.prototype.replace(),以便能够并排绘制N个图表。

function rocket(n = 1) {
  let props = ["|Rocket |", "|  #N   |"];
  let j = 0;
  let s = props[1].match(/\s+(?=\|)/)[0].length;
  triangle(n);
  line(n);
  sides(n);
  line(n);
  for (var i = 0; i < props.length; i++) {
console.log(
  props[i]
  .repeat(n)
  .replace(/(N)(\s+(?=\|))/g
  , (_, a, b) => ++j + (j >=10 ? " ".repeat(s-1) : b)));
  }
  line(n);
  sides(n);
  line(n);
  triangle(n); 
}

function triangle(n){
  var props = ["   / \\   ", "  /   \\  ", " /     \\ "];
  draw(props, n);
}

function line(n){
  var props = ["+-------+"];
  draw(props, n);
}

function sides(n){
  var props = ["|       |"];
  draw(props, n);
}

function draw(props, n) {
  for (var prop of props) console.log(prop.repeat(n));
}

rocket(15);