-1

Is it possible that the merging of sub variables fetches the constructed variable?

That's my script:

var a_b_c = 5000;

console.log(a_b_c); // 5000

var el_a = 'a';
var el_b = 'b';
var el_c = 'c';

console.log(el_a + '_' + el_b + '_' + el_c); // logs a_b_c

... what I would like to have is though:

console.log(el_a+'_'+el_b+'_'+el_c); // 5000

Is this anyhow possible?

Here is a fiddle:

https://jsfiddle.net/2ca9skg7/

isherwood
  • 58,414
  • 16
  • 114
  • 157
Philipp M
  • 3,306
  • 5
  • 36
  • 90

1 Answers1

1

var a_b_c = 5000;

console.log(a_b_c);

var el_a = 'a';
var el_b = 'b';
var el_c = 'c';

console.log(window[el_a+'_'+el_b+'_'+el_c]);

https://jsfiddle.net/oa3gw450/

or if it's in a function, you'll probably have to use eval:

(() => {
  var a_b_c = 5000;

  console.log(a_b_c);

  var el_a = 'a';
  var el_b = 'b';
  var el_c = 'c';

  console.log(eval(el_a+'_'+el_b+'_'+el_c));
})()
dave
  • 62,300
  • 5
  • 72
  • 93