简体   繁体   中英

How can I get the content of a variable that I don't know its name

Although this question is about datatables, it's not specifically about it.

I have datatables init stored in variables. The variable name varies as I have several datatables on the page. I am trying to collect the content of those variable by assembling the variable's name and I don't know how i can later use the 'string' I've assembled as a variable

For example:

var var_1_id_0 = $('.item1').datatable();
var var_1_id_1 = $('.item2').datatable();
var var_1_id_2 = $('.item3').datatable();

// later in the code.
var varname = 'var_1_id'+'_0';

// varname now holds the string 'var_1_id_0' which is the first variable.

My question is how can I use varname's string 'var_1_id_0' as the variable 'var_1_id_0'?

I hope that make sense.

Thanks

It is not possible. The closer solution is this one:

var datatable={};//A new Object.Arrays doesn't work property for this.

datatable['var_1_id_0'] = $('.item1').datatable();
datatable['var_1_id_1'] = $('.item2').datatable();
datatable['var_1_id_2'] = $('.item3').datatable();

// later in the code.
var varname = 'var_1_id'+'_0';
console.log(datatable[varname]);

Try it like this:

var varname = 'var_1_id'+'_0';

alert(window[varname]);

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