简体   繁体   English

我知道此代码无法正常工作,为什么我找到的代码可以工作? 是什么使错误的代码错了?

[英]I know this code does not work, why does the code that I found does? What makes the wrong code, wrong?

This is from some exercise in some coding book. 这是从一些编码书中的练习中得出的。 The goal is to use a for loop and jQuery to print your friends name on a different line; 目标是使用for循环和jQuery在不同的行上打印您的朋友姓名; but every time I open it the page becomes unresponsive. 但是每次我打开它时,页面都会变得无响应。 I want to know exactly why in full detail. 我想确切知道为什么如此详细。

This is the code that does not work: 这是无效的代码:

var friendsName = prompt("enter a friends name");

for(friendsName; friendsName !== null;){
    $("body").append("<p>" + friendsName + "<p>");
} 

this is the code that does: 这是执行以下操作的代码:

for(var listYourFriends;listYourFriends !== null;listYourFriends = prompt("enter a friends name"))
{

   if(listYourFriends !== undefined){$("body").append("<p>" + listYourFriends + " smells" + "</p>");
    }


    else if( listYourFriends === null){
        break;
    }
}

but now that I got the answer I have no idea why this code works but the other does not. 但是现在我得到了答案,我不知道为什么这段代码行得通,而其他代码行不通。 The other one, though it did set off some alarms for me, seemed to me like it should have made sense. 另一个虽然确实给我带来了一些警报,但在我看来,它似乎是有道理的。 can someone explain the differences between the two? 有人可以解释两者之间的区别吗?

Your code will go it to infinite loop because the condition friendsName !== null for for loop never gets false . 您的代码会将其转到无限循环,因为for循环的条件friendsName !== null永远不会for false For example when you enter some name into prompt it will not be changed again and will remain same throughout the code. 例如,当您在提示符下输入一些名称时,它将不会再次更改,并且在整个代码中将保持不变。

You need to update friendsName with new value in every loop. 您需要在每个循环中用新值更新friendsName

 var friendsName = prompt("enter a friends name"); for(friendsName; friendsName !== null;){ $("body").append("<p>" + friendsName + "<p>"); friendsName = prompt("enter a friends name"); } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 

Why code works? 为什么代码有效?

According to MDN the syntax for the for statement is 根据MDN, for语句的语法为

for ([initialization]; [condition]; [final-expression]) 

Here final-expression is the part which will be evaluated during each iteration. 在这里, final-expression是将在每次迭代期间评估的部分。 In the above code we are executing the following line during each iteration. 在上面的代码中,我们在每次迭代期间执行以下行。

friendsName = prompt("enter a friends name");

So we can put that at the place of [final-expression] and that will behave the same. 因此,我们可以将其放在[final-expression]的位置,并且其行为将相同。 So that's the reason the code given in question works. 这就是有问题的代码起作用的原因。

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

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