Javascript: inverting a boolean does not work
-
17-03-2021 - |
Вопрос
i am trying to invert a boolean value (toggle);
var current_state=$.cookie('state');
if(current_state==null) {
current_state=false;
}
console.log(current_state);
current_state=(!current_state);
console.log(current_state);
$.cookie('state', current_state, { expires: 7, path: '/' });
In my opinion the second console.log
should display the opposite of the first one, but both calls report false
. Whats up here?
Решение
Your $.cookie('state')
seems to be a string ("false
").
As a proof, see the following code (also in this jsfiddle):
var current_state='false';
if(current_state==null) {
current_state=false;
}
console.log(current_state);
var current_state=(!current_state);
console.log(current_state);
It outputs false
twice.
Why? Because you check if it is null and do not support other cases.
You can do something like this:
var current_state='false';
if(current_state==null ||
current_state==false ||
current_state=='false') {
current_state = false;
}else{
current_state = true;
}
console.log(current_state);
current_state=(!current_state);
console.log(current_state);
and your code will output boolean true
or false
first and then the opposite boolean value.
Другие советы
Are you sure that in the case that current_state
is not null
that it is actually a boolean value? Perhaps it's a string?
The problem is that current_state is not a boolean but a string
var current_state=$.cookie('state');
if(current_state==null) {
current_state=false;
}
console.log(current_state);
var current_state= current_state == 'false' ? "true" : "false"; // (!current_state);
console.log(current_state);
$.cookie('state', current_state);
Не связан с StackOverflow