简体   繁体   中英

Convert string literals in an array to variable name

I'm new to javascript. I am trying to store object variable names in an array but the way I'm doing it, the array values become strings. Is there a way to change these values from strings to the object variable names? In the following code, the last statement is what I would like to use but it generates "undefined" because, I think, it's seen as a string. Thanks!

var plan1 = {
  name: "Lisa",
  price: 5.00,
  space: 100
}

var plan2 = {
  name: "John",
  price: 2.00,
  space: 150    

}

var myArray = [];

for (var i = 0; i < 2; i++) {
  myArray[i] = "plan" + (i + 1);
}

alert(plan2.name);
alert(myArray[1].name);

You can't build the name like you are trying to do and get it to store the object with the same name. What you have in myArray is the strings "plan1" and "plan2" . You would have to do something like myArray[0] = plan1; myArray[1] = plan2; myArray[0] = plan1; myArray[1] = plan2; Then it should work in the array like you want it to.

Disclaimer: it's a very bad style, try to avoid it. Look at http://nedbatchelder.com/blog/201112/keep_data_out_of_your_variable_names.html

You can consider using eval :

for (var i = 0; i < 2; i++) {
  myArray[i] = eval("plan" + (i + 1));
}

Don't try to do that programmatically. Just build your array literal out of the parts that you want it to contain:

var plan1 = {
  name: "Lisa",
  price: 5.00,
  space: 100
};
var plan2 = {
  name: "John",
  price: 2.00,
  space: 150 
};
var myArray = [plan1, plan2];

Or even don't use those variables for the objects at all, and directly put them in the array structure:

var myArray = [{
  name: "Lisa",
  price: 5.00,
  space: 100
}, {
  name: "John",
  price: 2.00,
  space: 150    
}];

you can use

myArray[i] = window["plan" + (i + 1)];

working copy at http://plnkr.co/edit/7pY4Lcmx6wN1rQk9rklu?p=preview

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