1

我在 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   |
+-------+
|       |
+-------+
   / \
  /   \
 /     \
4

3 回答 3

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])
  }

}

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

注意:即使您并排打印不同的图表,这也会起作用。

于 2017-11-22T22:26:12.640 回答
1

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

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

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

于 2017-11-22T22:43:58.853 回答
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);

于 2018-01-10T03:50:09.600 回答