Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

110
Vistas
javascript eval with multiple variables

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 ...
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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));

about 4 years ago · Juan Pablo Isaza Denunciar

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar

0

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)

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda