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

153
Visualizações
Change variable with string instead of just accessing it

I can access a variable easily:

function accessVariable(accessFunction, variable) {
    var namespaces = accessFunction.split(".");
    for (var b = 0; b < namespaces.length; b++) {
        if (namespaces[b] != "") {
            try {
                variable = variable[namespaces[b]];
            } catch {
                variable = undefined;
            };
        };
        return variable;
    };

But updating this gotten variable is something that I don't know how to do.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

It's easiest if you use a separate function to update. This can take the new value as another argument.

Then you stop the iteration before the last item in namespace, and use that as the index to assign to.

function updateVariable(accessFunction, variable, value) {
  var namespaces = accessFunction.split(".");
  for (var b = 0; b < namespaces.length - 1; b++) {
    if (namespaces[b] != "") {
      try {
        variable = variable[namespaces[b]];
      } catch {
        variable = undefined;
      }
    }
  }
  if (variable) {
    variable[namespaces.pop()] = value;
  }
}

let obj = {a: {b:[{c: 10}]}};
updateVariable('a.b.0.c', obj, 20);
console.log(obj);

about 4 years ago · Juan Pablo Isaza Relatório

0

Define a single global-scoped variable, and put your variables there.

var Glob = {}; // globally scoped object

function changeVar(){
    Glob.variable1 = 'value1';
}

function SeeVar(){
    alert(Glob.variable1); // shows 'value1'
} 
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