Can I point to an array using a value with the same name as the array?

Viewed 36

I've got 50 different lists, called list1, list2, and so forth. I also have a function which rolls a random number between 1 and 50 and then stores the value in a variable called randomNumber, and what I want to do is to access the list with a matching number.

My attempt at access the list looked like this:

document.getElementById("demo").innerHTML = list + randomNumber;

One solution would be to put all 50 lists into one list, and then use the randomNumber to access the right list through index. I am however still curious if this can be done in a way similar to what I was decribing above the code though.

1 Answers

Inserting the arrays into another array and accessing them by their indexes (or assigning them to property values on an object and accessing them by their associated property names) is the right approach.

The only way to reference scoped variables by strings representing their names is by using eval().

However, I will echo the linked MDN article: Don't do this.

⚠️ Warning: Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use eval(). See Never use eval()!, below.

Here's an example of using eval to reference each of the arrays below:

const list1 = [1, 2, 3];
const list2 = [4, 5, 6];

console.log(eval('list' + '1')); // [1, 2, 3]
console.log(eval('list' + '2')); // [4, 5, 6]

And here's an example of the recommended approach:

const list1 = [1, 2, 3];
const list2 = [4, 5, 6];

// As an object:
const listNames = {
  list1,
  list2,
};

// As an array:
const lists = [
  list1,
  list2,
];

console.log(listNames['list' + '1']); // [1, 2, 3]
console.log(lists[0]); // [1, 2, 3]

console.log(listNames['list' + '2']); // [4, 5, 6]
console.log(lists[1]); // [4, 5, 6]

Related