问题
So i just started learning javascript, I'm in the functions module now and I was playing around with it and suddenly i ran into a doubt:
why is this:
if(x==true){
return 1;
}
different from this:
if(x){
return 1;
}
?
You see, i have this code:
function isAdult(age){
if(age >= 18){
return true;
}
return false;
}
function nameAndAge(string, boolean){
if(boolean == true){
var my_string = string + " is adult";
return my_string
}
var my_string = string + " is under age";
return my_string
}
var talisa_age = 22;
var talisa_name = "Talisa Maegyr";
var status = isAdult(talisa_age);
var str = nameAndAge(talisa_name,status);
console.log(str)
and regardless of the "talisa_age" value i get the following output:
"Talisa Maegyr is under age"
however, if i chaged the nameAndAge's validation to
if(boolean){
var my_string = string + " is adult";
return my_string
}
the code works as intended...
回答1:
If you console.log(typeof status)
you'll see it's a string. Why? The answer is that status
is a special variable, window.status, which no longer has any effect on the window status bar but is nonetheless converted back to a string (presumably for display) when assigned a value.
The standard states:
For historical reasons, the
status
attribute on the Window object must, on getting, return the last string it was set to, and on setting, must set itself to the new value. When theWindow
object is created, the attribute must be set to the empty string. It does not do anything else.
So, your conditional is if ("true" == true)
*, which is false even with coercion. Changing it to if ("true")
appears to work because nonempty strings are truthy.
If you name your variable something else like status_
the program behaves normally. Even better, avoid variable declarations in the global scope and/or use const
or let
which are preferable to var
and can help prevent weird bugs like this.
Minimal reproduction of the problem:
console.log(typeof status);
var status = 42;
console.log(typeof status);
A few possible fixes:
var status_ = 42;
console.log(typeof status_);
const status = 42;
console.log(typeof status);
(() => {
var status = 42;
console.log(typeof status);
})();
*: Note that some browsers treat window.status
as read-only, for example IE11. status
would be ""
in such cases and you'll get differently unusual behavior.
Further reading:
- What is the scope of variables in JavaScript?
- Is there any reason to use the "var" keyword in ES6?
- Const in JavaScript: when to use it and is it necessary?
来源:https://stackoverflow.com/questions/62479819/boolean-condition-is-always-false-when-using-status-true