简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM