0

我有这个对象

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

4 回答 4

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"
于 2012-12-13T22:03:47.323 回答
1

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

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;
于 2012-12-13T22:02:53.930 回答
0

使用父对象

var plans = {};
var plan_1 = new paymentPlan("unlimited", 0, -1, -1);
plans["plan_1"] = plan_1;
alert( plans["plan_"+plan_id.name] );
于 2012-12-13T22:04:02.643 回答
0

尝试使用eval().

alert(eval('plan_'+plan_id+'.name'));
于 2012-12-13T22:04:15.670 回答