简体   繁体   中英

Convert string to become variable

I have multiple variables containing JSON as string (received from AJAX).

data.output_data_1234

data.output_data_5678

I convert them to Array:

var outputdataarr = new Array(data.output_data_1234);

This works fine, but how do I add a number to the var name:

var outputdataarr = new Array('data.output_data_'+formid+'');

this one does not work.

formid contains a proper number.

This does not work too:

var outputvar = window['data.output_data_' + formid];
var outputdataarr = new Array(outputvar);

Please help. Thanks.

You probably mean, you need something like this:

var outputdataarr = new Array(data['output_data_'+formid]);

You can only use string in square brackets as an object field identifier. It cannot contain '.'.

UPDATE: However, you will probably need a loop to fill the whole array, eg

var outputdataarr = new Array();    
for (var i=1000; i<2000; i++) {
  outputdataarr.push(data['output_data_'+formid]);
}

Use [] instead of new Array is better.

var outputdataarr = [];
outputdataarr.push(data['output_data_'+formid]);
//and so on

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