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

147
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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