tanigame
tanigame

Reputation: 35

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)

Upvotes: 1

Views: 97

Answers (3)

Plutus
Plutus

Reputation: 183

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.

Upvotes: 0

evolutionxbox
evolutionxbox

Reputation: 4122

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.

Upvotes: 3

Unmitigated
Unmitigated

Reputation: 89412

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

Upvotes: 0

Related Questions