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?
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?
Use eval()
( But I will not prefer this method , you can find out the reason here : Why is using the JavaScript eval function a bad idea? )
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);
UPDATE : A better way is to use an object instead. Define the object property as your dynamic variable name. You can get the object property value by Bracket notation.
// defining object
var obj = {
price11: 100;
}
var i = 11;
// retrieve object property
var displayprice = obj['price' + i];
console.log(displayprice);
- Never use
eval()
. Object-Oriented JavaScript - Second Edition:eval()
can be useful sometimes, but should be avoided if there are other options. Most of the time there are alternatives, and in most cases the alternatives are more elegant and easier to write and maintain. "Eval is evil" is a mantra you can often hear from seasoned JavaScript programmers. The drawbacks of usingeval()
are:
- Security – JavaScript is powerful, which also means it can cause damage. If you don't trust the source of the input you pass toeval()
, just don't use it.
- Performance – It's slower to evaluate "live" code than to have the code directly in the script.- Use single
var
. Object-Oriented JavaScript - Second Edition: Consider a "single var" pattern. Define all variables needed in your function at the very top of the function so you have a single place to look for variables and hopefully prevent accidental globals.- Use object properties for dynamic names
var
obj,
i = 11,
displayprice;
obj.price11 = 100;
displayprice = obj['price' + i];
You can get objects's property dynamically: obj['price' + i] => obj['price11'] => 100