[英]If/else statements just do not seem to be working in Javascript and i don't know what I am doing wrong
I am struggling to get this to work for a Javascript magic 8 Ball, and for the life of me i cannot figure out what the issue is, so i am hoping someone on here will be able to tell me what I am doing wrong.我正在努力让它为 Javascript 魔术 8 球工作,对于我的一生,我无法弄清楚问题是什么,所以我希望这里的人能够告诉我我做错了什么。 I will pose the code as it is now:
我将按现在的样子摆出代码:
let userName = "Vince";
if (userName === true){
console.log(`Hello ${userName}`);
} else {
console.log(`Hello!`);
}
let userQuestion = "";
if (userName === true){
console.log(`${userName},You asked me \"${userQuestion}\"`);
} else {
console.log(`You asked \"${userQuestion}\"`);
}
I have also tried我也试过
let userName = "";
userName === true
? console.log(`Hello ${userName}`)
: console.log("Hello!");
let userQuestion = "";
userName === true
? console.log (`${userName},You asked me \"${userQuestion}\"`)
: console.log(`You asked \"${userQuestion}\"`);
No matter what i do here, it will only ever run the "else" section of code so i am getting this:无论我在这里做什么,它只会运行代码的“else”部分,所以我得到这个:
Hello!你好! You asked "will i win the lottery" It is decidedly so
你问“我会中彩票吗” 肯定是这样
I have no doubt that the answer is obvious and I am being dense, or i have just misunderstood something about truthy/falsey statements, but i am very close to pulling my hair out at this stage, so any help you can offer would be greatly appreciated.我毫不怀疑答案是显而易见的,而且我很密集,或者我只是误解了一些关于真假陈述的事情,但在这个阶段我非常接近于拔掉我的头发,所以你能提供的任何帮助都会很大赞赏。
i have switched the above around and tried loads of different things.我已经改变了上述内容并尝试了很多不同的东西。 Just a bit lost.
只是有点失落。
You are trying to compare two different data types: userName
is a String, while true
is a boolean value, that is why the if condition is never satisfied.您正在尝试比较两种不同的数据类型:
userName
是一个字符串,而true
是一个 boolean 值,这就是为什么永远不会满足 if 条件的原因。
The correct way to check for userName
would be:检查
userName
的正确方法是:
if (userName){
console.log(`Hello ${userName}`)
} else{
console.log(`Hello!`)
}
Your fault lies in the datatype youre checking.您的错在于您正在检查的数据类型。 You expect a bool but your are giving it a string.
你期望一个布尔值,但你给它一个字符串。
I assume you want to check if there is a name and not empty?我假设您想检查是否有名称而不是空的?
let userName = "Vince"
if (!!userName){ //Checks if username is not empty.
console.log(`Hello ${userName}`)
} else{
console.log(`Hello!`)
}```
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.