0

I want to be able to basically do this

let x = 1;
let `arr${x}`;

if ((i = 0)) `arr${x}` = [];
`arr${x}`.push(words);
console.log(`arr${x}`);

I have tried using eval()

let x = 1;
eval(`let arr${x}`);

if ((i = 0)) eval(`arr${x} = [];`);
eval(`arr${x}.push(${words})`);
console.log(eval(`arr${x}`));

But it's giving an error: Uncaught ReferenceError: arr1 is not defined In this line: eval(arr${x}.push(${words}));

4
  • 1
    eval is the only way, JS doesn't have a concept of dynamically created variable names. I'd suggest you to use a suitable data structure instead (ex. object). Notice, that i = 0 in the conditions doesn't do what you think it does. Commented May 14, 2024 at 5:41
  • 1
    Why not just use a list? Commented May 14, 2024 at 5:42
  • @Teemu Here is a link to codepen for the whole code, so you would understand better of what I'm trying to do: codepen.io/huz3y/pen/yLWNedW Commented May 14, 2024 at 5:51
  • Why not add that code right in the question, instead of linking it, as a Stack snippet? Commented May 14, 2024 at 5:55

1 Answer 1

1

You can't do this with variables, but you can very well do it with object properties. If the object you create it on happens to be the global object (window in browsers) this will also create a global variable:

let x = 1, words = "some words here", i = 0;
window[`arr${x}`] = undefined;

if (i===0) window[`arr${x}`] = [];
window[`arr${x}`].push(words);
console.log(window[`arr${x}`]);
console.log(arr1);

Sign up to request clarification or add additional context in comments.

1 Comment

This was what I was looking for!! You managed to answer me eventhough I gave very little context. Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.