很抱歉,我相信以前有人问过这个问题,但我似乎不能用正确的措辞来找到答案。我试着从Udemy那里学习Javascript,还有一个问题,你必须返回这个由星号组成的三角形,其中第一行是1星号,第2行是2,第3行是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);
发布于 2020-03-04 13:41:05
当您调用console.log()方法时,它将返回undefined (您可以在控制台规范中看到)。相反,每次循环迭代时,都需要将makeLine(i)的返回添加到tri字符串中(使用+=) (将其构建为一个大三角形)。然后,一旦你完成了,返回这个内置的字符串。
除此之外,您还应该在循环中的声明前面使用var/let,并在i=1处启动循环,因为您不希望在所得到的字符串中有一行0星:
/*
* 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
发布于 2020-03-04 13:35:45
您应该首先构建三角形,然后记录它,即将三角形变量中的所有行串联起来,然后返回:
// 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));https://stackoverflow.com/questions/60527229
复制相似问题