如何为JSON对象赋值

时间:2012-04-12 16:20:30

标签: javascript

我有以下代码不起作用。我试图将文本“John”推到对象的末尾。我对PHP更熟悉,这适用于PHP。

var data = {};
var field_name = "first_name";

data[field_name]['answers'][] = "John";

alert(data['first_name']['answers'][0]);

修改

我也尝试过以下操作,但没有用。

var data = {};
var field_name = "first_name";
var i=0;

data[field_name]['answers'][i] = "John";

alert(data['first_name']['answers'][0]);

2 个答案:

答案 0 :(得分:1)

试试这个:

var data = {};
var field_name = "first_name";
data[field_name] = {};
data[field_name].answers = [];
data[field_name].answers.push("John");

alert(data['first_name'].answers[0]);

答案 1 :(得分:0)

不能随意定义更多数组维度或动态扩展边界,就像PHP会乐意允许的那样。你需要做这样的事情(简写[]表示法也可以用来代替新的Array()。我只是喜欢这种方式。):

var data = {};
var field_name = "first_name";

//Create the new dimensions
data[field_name] = new Array();
data[field_name]['answers'] = new Array();
//Push the new element
data[field_name]['answers'].push("John");

alert(data['first_name']['answers'][0]);​​​​​​​​​​​​​