简体   繁体   English

基本JavaScript if if else if

[英]Basic JavaScript if vs. else if

My question is this: I'm new to JavaScript, I am trying to understand the difference between the " if { " and " else if { " statements. 我的问题是:我是JavaScript的新手,我试图理解“if {”和“else if {”语句之间的区别。 Thus far the only answers I have found are related to someone inheriting my code later, obviously no one is ever going to inherit my class project! 到目前为止,我发现的唯一答案与稍后继承我的代码的人有关,显然没有人会继承我的类项目! My question specifically is this: 我的具体问题是:

I am doing the rock paper scissor game project on codecademy. 我正在使用codecademy进行摇滚纸剪刀游戏项目。 My Math.random() method produces a random number. 我的Math.random()方法产生一个随机数。 I first implemented my code if (computerChoice <= 0.33){ 我首先实现了我的代码if(computerChoice <= 0.33){

and its alternative as: 及其替代方案:

if (computerChoice > 0.67){......    Which checked out and produced a viable answer. 

In its suggestion however it used the else if statement. 但是在它的建议中,它使用了else if语句。 My specific question is in either situation I essentially set a low range and a high range, leaving else to represent the middle. 我的具体问题是在任何一种情况下我基本上都设定了低范围和高范围,而其他方面则代表中间。 Else means not the previous condition. 否则意味着不是先前的条件。 But if my condition for a second if already logically excludes the previous answer (which would have to be logically excluded in the else if alternative anyway) what exactly is the difference and why use else if/ when would else if be necessary? 但是,如果我的条件已经在逻辑上排除了前一个答案(如果替代方案中必须在其他方面被逻辑排除),那究竟是什么区别以及为什么要使用其他if / when如果有必要呢?

My code follows: 我的代码如下:

Option one (else if): 选项一(否则如果):

var userChoice = prompt("do you want rock paper or scissors?");
var computerChoice = Math.random();

if (computerChoice <= 0.33){
  computerChoice = "rock";
}
else if (computerChoice >= 0.67){
 computerChoice = "scissors";
}
else {
 computerChoice = "paper";
}

console.log(computerChoice);

Option two (2 if's): 选项二(2个如果):

var userChoice = prompt("do you want rock paper or scissors?");
var computerChoice = Math.random();

if (computerChoice <= 0.33){
 computerChoice = "rock";
}
if (computerChoice >= 0.67){
 computerChoice = "scissors";
}
else {
 computerChoice = "paper";
}

console.log(computerChoice);

If-else if-else logic is more elegant than your second example because it will stop evaluating conditionals after the correct assignment has been made. If-else if-else逻辑比第二个例子更优雅,因为在完成正确的赋值后它将停止评估条件。

Consider how your second case (without else if) would work if computerChoice is 0.25. 如果computerChoice为0.25,请考虑第二种情况(如果没有其他情况)将如何工作。 The first if condition would evaluate to true and computerChoice would be reassigned to "rock." 第一个if条件将评估为true,而computerChoice将被重新分配为“rock”。 Instead of considering itself done, however, the logic would then proceed, and check to see if computerChoice >= 0.67. 然而,不是考虑自己完成,而是继续逻辑,并检查计算机选择是否> = 0.67。 Since computerChoice is now "rock," the interpreter will attempt to convert it to a numeric value. 由于computerChoice现在是“摇滚”,解释器将尝试将其转换为数值。 Since rock won't convert, my guess is your logic will, for now, work as intended. 由于摇滚不会转换,我的猜测是你的逻辑意志,现在,按预期工作。

However, consider a situation where you decide to define your entities -- rocks, paper, and scissors -- as an object, and to use the index of that object as the output of your processing. 但是,请考虑这样一种情况:您决定将实体(岩石,纸张和剪刀)定义为对象,并使用该对象的索引作为处理的输出。 For instance: 例如:

var myentities = 
{
    1: { name: "rock", image_url: "..." },
    2: { name: "paper", image_url: "..." },
    3: { name: "scissors", image_url: "..." }
};

And suppose you also decide to stop using the name of the object, but instead to use its ID. 并且假设您还决定停止使用对象的名称,而是使用其ID。 In that case, your first if would assign the value of 1 to computerChoice -- and then the second if would check to see if 1 >= 0.67. 在这种情况下,您的第一个if会将值1分配给computerChoice - 然后第二个if将检查是否1> = 0.67。 As a result, your code would (quite innocently) pick paper 100% of the time, confounding you greatly for a short while. 结果,你的代码会(非常天真地)100%的时间选择纸张,让你在很短的时间内感到困惑。

Moral of the story: unnecessary evaluation will never help you and may hurt you. 故事的道德:不必要的评价永远不会帮助你并可能伤害你。

If you are checking for different conditions of the same variable (or something like that) then else if is faster. 如果您正在检查同一变量的不同条件(或类似的东西),那么否则更快。 If it matches a condition, it executes and then you are done in the statement. 如果它与条件匹配,则执行,然后在语句中完成。 A whole bunch of if statements means the code has to run through every one of those no matter if it finds the first one true or not. 一大堆if语句意味着代码必须遍历其中的每一个,无论它是否找到第一个是真的。 Be aware though, with 'else if' you must be only looking for one of the conditions to match. 但请注意,使用'else if',您必须只查找其中一个条件才能匹配。 If you want it still to check anything after that, it will have to be another 'if' statement. 如果您希望在此之后仍然检查任何内容,则必须是另一个“if”语句。

But if my condition for a second if already logically excludes the previous answer (which would have to be logically excluded in the else if alternative anyway) what exactly is the difference and why use else if/ when would else if be necessary? 但是,如果我的条件已经在逻辑上排除了前一个答案(如果替代方案中必须在其他方面被逻辑排除),那究竟是什么区别以及为什么要使用其他if / when如果有必要呢?

=> None, however the else statement enforces it in case you made a mistake in your "logical exclusion". =>无,但是如果你在“逻辑排除”中犯了错误,else语句会强制执行它。

Even if it's a bit outside the scope of your question it's also worth noting that there is no "else if" construct in JavaScript. 即使它有点超出了你的问题范围,也值得注意的是JavaScript中没有“else if”结构。 When you write: 当你写:

if (...) {

} else if (...) {

}

what you are basically doing is: 你基本上做的是:

if (...) {

} else {
  if (...) {

  }
}

it works because you can either pass any statement after the else keyword. 它的工作原理是因为你可以在else关键字之后传递任何语句。 See http://www.ecma-international.org/ecma-262/5.1/#sec-12.5 :-) http://www.ecma-international.org/ecma-262/5.1/#sec-12.5 :-)

Update 1 更新1

if (weight <= 130) {
  fighter = "lightweight";
} else if (weight >= 205) {
  fighter = "heavyweight";
} else {
  fighter = "middleweight";
}

which, in javascript, is equivalent to: 在javascript中,相当于:

if (weight <= 130) {
  fighter = "lightweight";
} else {
  if (weight >= 205) {
    fighter = "heavyweight";
  } else {
    fighter = "middleweight";
  }
}

Update 2 更新2

In your original post, Option 2, you do: 在您的原始帖子选项2中,您执行以下操作:

if (computerChoice <= 0.33){
  computerChoice = "rock";
}

if (computerChoice >= 0.67){
 computerChoice = "scissors";
}
else {
  computerChoice = "paper";
}

If computerChoice is <= 0.33, what's going to happen is the following: 如果computerChoice <= 0.33,将会发生以下情况:

if (0.33 <= 0.33) ... // => computerChoice = "rock"

if ("rock" >= 0.67) ... else [THE ELSE PART IS EXECUTED!]

So basically computerChoice will be "paper" any time it should be "rock". 因此,计算机选择基本上应该是“纸”,它应该是“摇滚”。 You will have "paper" 67% of the time and "scissors" 33% of the time! 67%的时间你会有“纸”,33%的时间会有“剪刀”! This happens because Javascript doesn't throw an error when you try to compare values of different types (ie here a string, "rock", and a number "0.67"; instead it tries to convert the values in the same type by some magical coercion rules ( http://webreflection.blogspot.be/2010/10/javascript-coercion-demystified.html ) and then happily answer "false!". As a math major I could probably scare you by saying that due to those coercion rules you can prove, in javascript, that true = false... 发生这种情况是因为当您尝试比较不同类型的值时,Javascript不会抛出错误(即此处为字符串,“摇滚”和数字“0.67”;相反,它会尝试通过某些神奇的方式转换相同类型的值强制规则( http://webreflection.blogspot.be/2010/10/javascript-coercion-demystified.html ),然后高兴地回答“假!”。作为一个数学专业,我可能会因为那些强制而吓唬你您可以在javascript中证明的规则,即true = false ...

PS: I just noticed Kevin Nielsen explained it above way better than I did. PS:我刚才注意到凯文尼尔森比我更好地解释了它。 Here you go! 干得好!

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

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