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

138
Vistas
Convert string into variable in array automatically

I have a problem when Im trying to convert a string to a variable in an array.

The variables are:

const n = 1; const s = -1;

The array string:

let walk = ['n', 's', 'n', 's', 'n', 's', 'n', 's', 'n', 'n']; 

I want to convert automatically to this variable array:

let walk = [n, s, n, s, n, s, n, s, n, n];

I'm trying to split but the array still string not a var:

let text = walks.toString().split(',').join('-')
console.log(text)
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You could put s and n into an object.

const variables = {
  n: 1,
  s: -1
};

let walk = ['n', 's', 'n', 's', 'n', 's', 'n', 's', 'n', 'n'];

console.log(
  walk.map(variable => variables[variable])
)

See this question for more info on accessing variables via another variable.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You could use eval, but it is usually not recommended.

const n = 1; const s = -1;
let walk = ['n', 's', 'n', 's', 'n', 's', 'n', 's', 'n', 'n'].map(eval);
console.log(walk);

about 4 years ago · Juan Pablo Isaza Denunciar

0

As @Unimitigated said, eval() is not recommended to use.

For more details refer to this link Never use eval()!

For a better way, without eval(). You can try this approach

const n = 1; const s = -1;
const array = [];
let walk = ['n', 's', 'n', 's', 'n', 's', 'n', 's', 'n', 'n'].map(value => {
  return Function('"use strict";return (' + value + ')')();
}); 

I hope this would be useful.

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