Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

114
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda