几乎所有计算机语言中非常重要的一部分是条件语句,尤其是if / else语句。 这是一个例子。
if(16==16){
window.alert("Yes, 16 does equal 16! Amazing!");
}
else {
window.alert("Wait a second... 16 is not equal to 16?");
}
这是一个解释。
此代码表明,如果16等于16,
“是的,16等于16!太神奇了!” 将显示在警报框中。 如果不是,则“等一下... 16不等于16?” 将显示在警报框中。 请注意,如果使用两个等号(而不仅仅是一个)比较两个数字,则在括号中。
if(16==16)
原因是=是一个赋值运算符,用于为变量赋值,而==是一个比较符,用于比较两个值。
其他比较运算符包括<=(小于或等于),> =(大于或等于),=,>和<。
但是,上面显示的代码并不是真正有用的。 一种使它有用的方法如下所示:
var age=prompt("What is your age?");
if(age<6){
window.alert("You are under 6. You need the parental password.");
var pass=prompt("Type in the password to continue.");
if(pass=="parentpassword"){
window.alert("The password you inserted is correct. Go on!");
window.location="google.com";
}
else{
window.alert("Your password is wrong");
}
}
else{
window.alert("You are over 6. You are good to go.");
window.location="google.com";
}
如您在上面的代码中看到的,if / else语句非常有帮助,您还可以将if / else语句放在其他if / else语句(也称为嵌套if / else语句)中。
它们构成许多计算机程序的基本部分。
尝试尝试一下!
From: https://bytes.com/topic/javascript/insights/947864-how-work-if-else-statements-javascript