将javascript对象属性设置为变量

时间:2013-04-30 03:18:46

标签: javascript

如何将对象的属性设置为变量?该变量等于表单文本字段值。当我显示obj.property对象时,obj[property]undefined error都会给我一个mycar

function auto(manufacturer,model,engine_size,year,color,price) 
{
    this.manufacturer = manufacturer;
    this.model = model;
    this.engine_size = engine_size;
    this.year = year;
    this.color = color;
    this.price = price;
}

var mycar = new auto();

var a = document.form.num1.value;
mycar.manufacturer = a;
mycar[manufacturer] = a;

对不起。这是我的所有代码http://jsfiddle.net/vzqjv/

我试图将我的对象属性设置为变量a,在某些验证之后它等于表单文本字段值以查看它是否结束。

4 个答案:

答案 0 :(得分:1)

mycar.manufacturer = aa分配给mycar名为manufacturer的媒体资源。

mycar[manufacturer] = aa分配给mycar的属性,其名称与变量manufacturer的值相同。你可能意味着mycar["manufacturer"] = a

答案 1 :(得分:1)

第二种符号

mycar[manufacturer] = a;

应该是

mycar["manufacturer"] = a;

第一种符号应该有用。你是否以我们看不到的方式修改mycar?

我的猜测是未定义的错误实际上就在这一行:

var a = document.form.num1.value;

正确定义了吗?

答案 2 :(得分:1)

您尚未声明变量manufacturer,因此在执行mycar[manufacturer] = a;时未定义。你需要定义它

var a = document.form.num1.value,
    manufacturer = "manufacturer";
mycar.manufacturer = a;
mycar[manufacturer] = a;

或使用引号:

var a = document.form.num1.value;
mycar.manufacturer = a;
mycar["manufacturer"] = a;

答案 3 :(得分:0)

你没有给出auto的定义。我猜你没有制造商的财产。另一种方法是做

var mycar = {};
var a = document.form.num1.value;
mycar.manufacturer = a;