从另一个变量创建JavaScript变量名称

时间:2012-12-13 22:00:57

标签: javascript variables object reference

我有这个对象

function paymentPlan(name, price, days, active){
        this.name=name;
        this.price=price;
        this.days=days;
        this.active=active;
    }

    var plan_1 = new paymentPlan("unlimited", 0, -1, -1);
    var plan_2 = new paymentPlan("starter", 100, 7, 2);

我需要通过从另一个变量构建变量实例来选择一个对象实例,实际上是将数字添加到引用的末尾

例如,如果我需要在选择时打印出plan_2的名称,我需要像这样构建引用

var plan_id = 2;

alert( plan_+plan_id.name ); 

我该怎么做?

4 个答案:

答案 0 :(得分:4)

您最好的方法是将计划存储在array

var plans = [];
plans.push(new paymentPlan("unlimited", 0, -1, -1));
plans.push(new paymentPlan("starter", 100, 7, 2));

var plan_id = 1;
alert(plans[plan_id].name); // "starter"

答案 1 :(得分:1)

如果您全局定义变量,则可以使用window object:

window["plan_" + plan_id].name;

但是,您可以始终初始化本地定义的对象内的变量,例如:

var plans = {
    plan_1 : new paymentPlan("unlimited", 0, -1, -1),
    plan_2 : new paymentPlan("starter", 100, 7, 2)
};

plans["plan_" + plan_id].name;

答案 2 :(得分:0)

使用父对象

var plans = {};
var plan_1 = new paymentPlan("unlimited", 0, -1, -1);
plans["plan_1"] = plan_1;
alert( plans["plan_"+plan_id.name] );

答案 3 :(得分:0)

尝试使用eval()

alert(eval('plan_'+plan_id+'.name'));