这个javascript代码运行成功,但我认为它没有通过"else"语句,因为它没有打印控制台。。。为什么?
i = 0;
for(var i=1; i<4; i++) {
var crazy = prompt("would you marry me?");
if(crazy === "Yes"|| "yes") {
console.log("hell ya!");
}
/* when it asks "will you marry me" and if the user says either "No" or "no", it does't print "ok..I'' try again next time". instead, it still says "hell ya !" */
else if (crazy ==="No" ||"no") {
console.log("ok..I'll try again next time !");
}
}
var love = false;
do {
console.log("nonetheless, I LOVE YOU !");
}
while(love);
试试这样的东西,
if(crazy.toUpperCase() === "YES") {
console.log("hell ya!");
}
试试这个。。不过代码不错。。这是向某个怪胎求婚吗?
i = 0;
for(var i=1; i<4; i++) {
var crazy = prompt("would you marry me?");
if(crazy === "Yes"|| crazy ==="yes") {
console.log("hell ya!");
}
/* when it asks "will you marry me" and if the user says either "No" or "no", it does't print "ok..I'' try again next time". instead, it still says "hell ya !" */
else if (crazy ==="No" ||crazy === "no") {
console.log("ok..I'll try again next time !");
}
}
var love = false;
do {
console.log("nonetheless, I LOVE YOU !");
}
while(love);
以下是解释:
crazy === "Yes" || "yes"
这句话的作用如下:
- 比较
crazy
是否与字符串"Yes"
相同 - 如果它们不相同,则"使用"
"yes"
将其放入if
语句中,即可得到以下内容:
- 执行
if
块中的所有内容,- …如果
crazy
与"Yes"
相同,或 - …如果
"yes"
- …如果
在if
语句中,"yes"
本身意味着什么?评估为true
。
每个不是空字符串的字符串被评估为true
,并且每个空字符串被评估为由false
。请参阅MDN关于Boolean
和falsy值的文章。
您可以通过在控制台中键入以下双否定表达式来验证这一点:
!!"yes"; // true
!!"test"; // true
!!""; // false
你需要做的是第二次比较:
if(crazy === "Yes" || crazy === "yes")
和
else if(crazy === "No" || crazy === "no")
替代方法包括仅用于一个比较的crazy.toLowerCase() === "yes"
或["Yes", "yes"].includes(crazy)
。