简体   繁体   中英

JS: how do I concatenate a variable into a API call with the dot syntax?

I am trying to pass a parameter in a function, which I will use in a Highcharts file.

function getID (ID) {
    chart+ID+.series[0].update({
        ....do something
    )};
}

When I try to concatenate the ID that I get from the function, to the update call; I get an error saying

unexpected token "."

How do I use the ID in the update function? I thought that the + sign would concatenate strings, so

chart+ID+.series[0]

is the same as, with ID='1', to

chart1.series[0] 

If chart1 is a global variable, you can do:

window['chart'+ID].series[0].update(...);

because global variables are automatically turned into properties of the window object.

If it's not a global variable, you can't do this. It would be best to make chart an array, rather than having chart1 , chart2 , etc. Then you could do:

chart[ID].series[0].update(...);

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