I want to use eval to calculate the following string with multiple varaibles I have all the variables stored in my object
let myVars = {
a : 10,
b : 20,
c : 30,
}
let str = "a b c 10"
// how to evaluate the string ...
CodePudding user response:
I'm not sure if I understood your question, but I will try my best to answer.
The eval()
method will automatically get the variables from the global context. If you want to get the result, just save the result from the eval()
function.
// Object destructuring for easier readability
let { a, b, c } = {
a : 10,
b : 20,
c : 30,
}
let str = "a b c 10";
const total = eval(str);
console.log(total); // Should be: 70
The code above will return the result from the mathematical operation.
However, you should never use eval()
, as it can run any code arbitrarily.
CodePudding user response:
You could replace the (unknown) variables and use eval
(cave!) for getting a result.
let
values = { a: 10, b: 20, c: 30 },
str = "a b c 10";
str = str.replace(/[a-z0-9_] /g, s => values[s] ?? s);
console.log(eval(str));
CodePudding user response:
You have to mention that a b c... are for the myVars object so you have different ways:
let myVars = {
a : 10,
b : 20,
c : 30,
}
let str = "myVars.a myVars.b myVars.c 10"
console.log(eval(str))
Although I don't suggest this way to you because here we can use that without eval so that will be easier.
Another way is to use Regex:
let myVars = {
a : 10,
b : 20,
c : 30,
}
let str = "a b c 10"
const arrayName="myVars"
str=str.replace(/([a-z] )/gi,arrayName ".$1")
console.log(eval(str))
Here you add the object name behind the variables dynamically with Regex.
Or simply you can do what you want without eval (If you want):
let myVars = {
a : 10,
b : 20,
c : 30,
}
let sum=Object.values(myVars).reduce((partialSum, a) => partialSum a, 0) 10;
console.log(sum)
CodePudding user response:
While remembering that Eval is Evil since it allows for arbitrary code execution, you can use the with
block here to change the eval statement's global namespace:
let myVars = {
a: 10,
b: 20,
c: 30,
};
let str = "a b c 10";
let result = null;
with (myVars) {
result = eval(str);
}
console.log(result); // logs 70
Again, I do not recommend using eval
.