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

185
Views
Using a variable in place of an array

I have a number of arrays I'm using for my first Chrome extension. I want to use a different array for my extension depending on what a value is in a specific variable (locationVal), which is a number between 1-4. Here is the function that decides that:

if (locationVal === 1) {
arrayToUse = 'firstList';
} else if (locationVal === 2) {
    arrayToUse = 'secondList';
} else if (locationVal === 3) {
    arrayToUse = 'thirdList';
} else if (locationVal === 4) {
    arrayToUse = 'fourthList';
} else {
    console.log("setArray function error");
}
chrome.storage.local.set({arrayToUse});

The firstList, secondList, etc. are my arrays, which are declared as:

let firstList = [];
let secondList = [];
let thirdList = [];
let fourthList = [];

The main thing I'm wondering, is how will the arrayToUse variable be used as an array name in a settings such as this:

chrome.storage.local.get({arrayToUse: []}, function(items) {
  if (!chrome.runtime.error) {
    arrayToUse = items.arrayToUse;
  }
});

and

chrome.storage.local.set({arrayToUse : arrayToUse}, function() {
if (!chrome.runtime.error)....

I think that is being used as a string as-is and it is causing an issue there. If I put in one of my arrays directly, the program works fine.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I'd recommend using a map to store references to your arrays. This way you can access those by a string identifier, which can be the same as the variable name of a particular array. This string can then be saved to the localStorage.

Something like:

let firstList = [1, 2, 3];
let secondList = [4, 5, 6];
let map = new Map();
map.set("firstList", firstList);
map.set("secondList", secondList);

let arrayToUse = "secondList";
console.log(map.get(arrayToUse));

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!