Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!