[英]What is the difference between these two loops? Why is one working and the other is not?
I want to know why is it that when I add a variable with a value of an empty string(") the loop works but when i remove it, the loop ...doesn't seem to loop within this function... 我想知道为什么当我添加一个值为空string(“)的变量时,该循环有效,但是当我将其删除时,该循环似乎并没有在该函数中循环...
Here is the first loop: 这是第一个循环:
function laugh(num) {
var laugh = "ha";
for (var i=0; i<=num; i++){
laugh;
}
return laugh + "!";
}
console.log(laugh(3));
And here is the second one: 这是第二个:
function laugh(num) {
var string = "";
var laugh = "ha";
for (var i=1; i<=num; i++){
string += laugh;
}
return string + "!";
}
console.log(laugh(3));
The first returns "ha!" 第一个返回“ ha!” while the second returns the correct amount of ha's ...which is "hahaha!" 而第二个返回正确数量的ha ...即“ hahaha!”
why does adding an empty string make it work? 为什么添加一个空字符串使其起作用? Beginner by the way...I really don't want to move on to the next lesson until I have fully understood what is going on. 初学者...我真的不希望继续下一课,直到我完全了解正在发生的事情。 Thanks so much! 非常感谢!
That is because all you're doing in the first loop is a statement: 那是因为您在第一个循环中所做的只是一个语句:
laugh;
//Equivalent to
"ha";
In the second loop, you are concatenating a new string to string
: 在第二个循环中,您将一个新字符串连接到string
:
string += laugh;
You need to do this concatenation otherwise it will only return ha!
您需要执行此串联,否则只会返回ha!
: :
function laugh(num) { var laugh = "ha"; for (var i = 0; i <= num; i++) { laugh += "ha"; } return laugh + "!"; } console.log(laugh(3));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.