I have a little problem, I'm using JSLT to pass some variables from JSP to JavaScript
In this case they are two booleans
They are being created as 'false'
or 'true'
, they are passed to me as a string
When using them in a JavaScript function I have a small inconvenience
The only way that has worked for me is like this
if (b1 == 'false' && b2 == 'true') {
console.log("Entre al if numero 4");
}
But I want to avoid that usage. I even tried using Boolean but it didn't work for me
Is there a way to pass that string to Boolean?
Or maybe you can tell me the best way to work those booleans?
var b1 = 'false'
var b2 = 'true';
if (b1 && b2) {
console.log("Entre al if");
}
if (Boolean(b1) && Boolean(b2)) {
console.log("Entre al if numero 2");
}
if (b1 == false && b2 == true) {
console.log("Entre al if numero 3");
}
if (b1 == 'false' && b2 == 'true') {
console.log("Entre al if numero 4");
}
In the JSLT I just do this:<c:set var="hasError" value="false"/>
and to pass it to JS I do thisvar hasError = '<c:out value="${hasError}"/>'
I think maybe since you have the variables declared you could cast them by passing them as an argument to the Boolean object .
So:
If now both to the variables:
b1
andB1
you make them atypeof
you will see that you get different data types:The above results in:
If now, for example, we directly print the value assigned to each of the variables, we will notice the difference:
If we now use both variables inside a pair of conditionals like so:
So we get as output:
You can use JSON.parse() to convert strings to JavaScript objects
Another way is to make use of eval()
JSON.parse() is commonly used to read json files, but you can use it like this. and eval() is used to convert strings to ._ code. , I guess eval is the best way ?