这实际上是我编码的第一件事,而且我是自学成才的,所以我确定这是一团糟,并且我犯了一个愚蠢的错误,但是经过一个小时的查找,然后尝试了一下,无法解决这个问题。
为了尝试自学基本的javascript概念,我编写了一个与您进行生存对话的文本机器人。问题是,无论用户输入什么,都将连续打印whatDream条件的所有if语句。谁能告诉我我在这里搞砸了吗?如果我的方法不好,我很抱歉-我正在做的事情100%来自自我教学,让自己无法学习,我将不胜感激。
function yesHappy (){
alert ("Good for you. To be happy as a human is a great gift.");
alert ("The content human starts over again everyday, in spite of all they know, against all they know.");
alert ("If one advances each day confidently in the direction of their dreams, and endeavors to live the life which they have imagined, they will meet with a success unexpected in common hours.");
var g = 0
while (g < 2) {
g = 0
var whatDream = prompt ("What is your dream?");
if (whatDream === "success" || "Success" || "power" || "Power" || "wealth" || "Wealth"){
alert ("That is a goal that takes much will in the earthly domain, and is not one I can readily reccomend.");
alert ("But, read your fate, see what is before you, and walk into futurity.");
g = 3
}
if (whatDream === "friends" || "Friends" || "family" || "Family" || "love" || "Love"){
alert ("To surround oneself with others fulfills a basic human goal to be social, thus your dream is only natural.");
alert ("Properly speaking, a human has as many social selves as there are individuals who recognize them.");
alert ("To all of these you surround yourself with, see in your goals only to show your true social self.");
g = 3
}
if (whatDream === "fun" || "Fun" || "charity" || "Charity" || "faith" || "Faith" || "travel" || "Travel"){
alert ("These are honorable dreams, chosen to bring joy to yourself and others.");
alert ("Above all however, avoid falsehood, especially falseness to yourself.");
alert ("Be true to your purpose.");
g = 3
}
if (g === 0){
alert ("Though knowledge is the plague of life, and consciousness an open wound in its heart, I am still sad to say I don't know what you mean.");
alert ("Let's try that again.");
}
}
}
答案 0 :(得分:0)
您需要重构所有条件语句。例如:这个
if (whatDream === "success" || "Success" || "power" || "Power" || "wealth" || "Wealth")
必须将其翻译为:
if (whatDream === "success" || whatDream === "Success" || whatDream === "power" || whatDream === "Power" || whatDream === "wealth" || whatDream === "Wealth")
您想做什么?:检查whatDream是否等于其中的任何一个。或者,您可以使用数据结构并使用一种方法来检查字符串是否存在于该数据结构中,但是以上是您要做的最简单的重构。
Javascript具有“真”和“假”值。像“ Success”这样的字符串映射为true,而“”映射为false。因此,您的条件总是评估为true,因为长度大于0的字符串是“真实的”。这可能是您需要的更多解释,但重要的是要在将来的javascript开发中知道这一点。
本质上,您的问题是您没有在布尔逻辑中检查whatDream的值。我确实修复了上面的简单重构。
如果您感到好奇:您可以在此处阅读真实值和虚假值: