questions
Background: The key value read from cookies is ‘false’, and the problem arises when strings are used as a criterion
In the JS world, 0, -0, null, “”, false, undefined, or NaN can be automatically converted to Boolean false, but string “false” is not equal to false, if(“false”) is equal to true.
According to the W3C:
var myBoolean=new Boolean(a);// All of the following lines create Boolean objects with an initial value of false.
var myBoolean=new Boolean(a);var myBoolean=new Boolean(0);
var myBoolean=new Boolean(null);
var myBoolean=new Boolean("");
var myBoolean=new Boolean(false);// False without single quotes
var myBoolean=new Boolean(NaN);
// All of the following lines of code create Boolean objects with an initial value of true:
var myBoolean=new Boolean(1);
var myBoolean=new Boolean(true);
var myBoolean=new Boolean("true");
var myBoolean=new Boolean("false");// The single quoted string false eventually equals true
var myBoolean=new Boolean("Bill Gates");
Copy the code
Therefore, if a string ‘false’ is returned from a cookie or background, it cannot be used as a criterion directly.
The solution
- Ternary operator conversion
let bool = result === 'false' ? false : true
Copy the code
- The index
let bool = {
'true': true.'false': false}; bool[ v ] ! = =undefined ? bool[ v ] : false;
Copy the code
- JSON.parese
This should be the most convenient and concise method
JSON.parse('false') // false
JSON.parse('true') //true
Copy the code
- Use 0,1 instead of using string ‘ture’, which is ‘false’
let target = '0'
letbool = !! +targetCopy the code
This is a better solution found so far, if there is a better, more elegant way, welcome to post
The resources
Connection address