繁体   English   中英

Console.logging 然后在 javascript 函数中返回 console.log

[英]Console.logging and then returning the console.log within a javascript function

抱歉,我确定以前有人问过这个问题,但我似乎无法正确地表达出来以找到答案。 我试图从 Udemy 学习 Javascript,有一个问题,你必须返回这个由星号组成的三角形,其中第一行是 1 个星号,第二行是 2,第三行是 3 等等,直到 10 行星号。 如果我不够清楚,请参阅此链接

我可以 console.log 三角形,但一旦我控制台记录它,我似乎无法返回它。 请有人解释我需要在哪里退货。 我已经尝试了所有我能想到的方法,但一旦我添加了“buildTriangle 函数”的返回值,就会不断得到未定义或没有答案。

 /* * Programming Quiz: Build A Triangle (5-3) */ // creates a line of * for a given length function makeLine(length) { var line = ""; for (var j = 1; j <= length; j++) { line += "* "; } return line + "\\n"; } // your code goes here. Make sure you call makeLine() in your own code. function buildTriangle(length){ var tri=''; for(i=0;i<=length;i++){ tri=console.log(makeLine(i)); } return tri; } // test your code by uncommenting the following line buildTriangle(10);

您应该首先构建三角形然后记录它,即连接三角形变量中的所有行并返回:


// creates a line of * for a given length
function makeLine(length) {
  var line = "";
  for (var j = 1; j <= length; j++) {
      line += "* ";
  }
  return line + "\n";

}

// your code goes here.  Make sure you call makeLine() in your own code.
function buildTriangle(length){
  var tri='';
  for(i=0;i<=length;i++){
      tri+=(makeLine(i));
  }
  return tri;
}


// test your code by uncommenting the following line
console.log(buildTriangle(10));

当您调用console.log()方法时,它将返回undefined (您可以在控制台规范中看到)。 相反,每次循环迭代时,您都需要将makeLine(i)的返回添加到您的tri字符串中(使用+= )(以将其构建为一个大三角形)。 然后,完成后,返回该构建的字符串。

除此之外,您应该在循环中的声明前使用var/let并在i=1开始循环,因为您不希望结果字符串中出现一行零星:

 /* * Programming Quiz: Build A Triangle (5-3) */ // creates a line of * for a given length function makeLine(length) { let line = ""; for (let j = 1; j <= length; j++) { line += "* "; } return line + "\\n"; } // your code goes here. Make sure you call makeLine() in your own code. function buildTriangle(length) { let tri = ''; // \\/ -- add let/var here (doesn't effect output in this case) and initialize it to 1 for (let i = 1; i <= length; i++) { tri += makeLine(i); // call makeLine(i) which returns a string } return tri; // return the triangle string } // test your code by uncommenting the following line console.log(buildTriangle(10)); // log the string

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM