mkawa mkawa - 6 months ago 10
Javascript Question

How to append variable value to another variable

How to append var value to another var

var price11 = 100;
var i = 11;
var displayprice;
displayprice= price + 'i'; // should assign 100(value of price11) to displayprice.


Is it possible?

Answer

Use eval()

var price11 = 100;
var i = 11;
var displayprice;
displayprice = eval('price' + i);

console.log(displayprice);


If it's in global context then get it from window object

var price11 = 100;
var i = 11;
var displayprice;
displayprice = window['price' + i];

console.log(displayprice);