简体   繁体   中英

Javascript using a variable value as a name reference

Been searching online and tried a couple of fixes which haven't worked for me so was wondering if somebody else could help me sort this issue.

Basically I have attached some code to this which shows a function receiving a zone (zone is a number/there are only ever 3 zones 1,2,3). I then have 3 datasets called data1, data2, data3 which I want to reference using the zone number passed. But I need to keep data1, data2 & data3 all as separate arrays as they are then inserted into a chart (chartjs).

The function is called when the uses presses a switch on or off, there are 3 buttons one for each zone to enable that data set to show on the graph then when switched off it will remove that zones dataset.

Any help would be great, Kieran

    var data1 = [];
    var data2 = [];
    var data3 = [];

    // Adds/removes data sets from the chart
    function redrawChart(zone){
        var dataSet = "data"+zone;
        dataSet.push(7,8,8,9,10);

        historyChart = new Chart(document.getElementById('ns-popout-graph').getContext("2d")).Line(newData);
    }

You don't really have many options in this case. The cleanest one is to use object to hold arrays, then constructing dynamic key is easy:

var datas = {
    data1: [],
    data2: [],
    data3: []
};

// Adds/removes data sets from the chart
function redrawChart(zone) {

    var dataSet = datas["data" + zone];
    dataSet.push(7,8,8,9,10);

    // ...
}

Another approach could be eval but this is not recommended way to solve this problem. Note, that if data variables are defined in global namespace ( window ) you could still use window['data' + zone] but I hope you don't pollute global scope, do you? :)

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