[英]When I store the function in a variable, it prints out a slightly different result? (“undefined” thrown in at the end)
[英]Why appear undefined in the end of for-loop in JavaScript when I try to prints out layers of stars?
我尝试编写一个名为“stars”的 function,它按以下模式打印出星星层:
stars(1);
// *
stars(4);
// *
// **
// ***
// ****
这是我的代码:
function stars(n){
let result="";
for(let i=1;i<=n;i++){
result +="*" ;
console.log(result);
}
}
console.log(stars(1));
console.log(stars(4));
但是,事实证明是:
"*"
undefined
"*"
"**"
"***"
"****"
undefined
我试图拆开循环,但仍然无法弄清楚为什么会出现“未定义”。 谢谢!
function stars(n){
let result="";
for(let i=1;i<=n;i++){
result +="*" ;
console.log(result);
}
}
stars(1);
stars(4);
stars 是一个 function,它什么都不返回,然后控制台记录它记录未定义。
你应该只调用 stars(x),而不是使用控制台。因为你的 function 没有返回任何东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.