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