簡體   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