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);
-
1What you're trying to do doesn't sound well. Your application design is already broken if you have to do so.zerkms– zerkms2014年06月30日 22:26:29 +00:00Commented Jun 30, 2014 at 22:26
4 Answers 4
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));
}
3 Comments
var plans = {1: {...smth...}, 2: {...smth else...}}. It's just harder to control all these separate variables. What if you need to copy all of them or do smth else? And eval is a bad practice too because you can easily add unnecessary complexity with it, just moving some logic inside eval call bit by bit.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; Then it should work in the array like you want it to.
Comments
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
}];
Comments
you can use
myArray[i] = window["plan" + (i + 1)];
working copy at http://plnkr.co/edit/7pY4Lcmx6wN1rQk9rklu?p=preview
4 Comments
plan1 is a global variable?Explore related questions
See similar questions with these tags.