覆盖jQuery对象的问题

时间:2014-12-12 04:59:10

标签: jquery json

我有以下jQuery代码,但它没有给出预期的输出。

$serize = [];
$obj = {};
$input_data = [22,33,44];
$obj.name = "Sadik";
$obj.data = $input_data;
$serize.push($obj); 

$input_data = [11,21,32];
$obj.name = "Palsaniya";
$obj.data = $input_data;
$serize.push($obj); 

alert(JSON.stringify($serize));

当前输出

[{"name":"Palsaniya","data":[11,21,32]},{"name":"Palsaniya","data":[11,21,32]}]

预期输出

[{"name":"Sadik","data":[22,33,44]},{"name":"Palsaniya","data":[11,21,32]}]

1 个答案:

答案 0 :(得分:1)

试试这个:JSFIDDLE

您只需重新初始化$obj

即可
$serize = [];
$obj = {};
$input_data = [22,33,44];
$obj.name = "Sadik";
$obj.data = $input_data;
$serize.push($obj); 

$obj = {};
$input_data = [11,21,32];
$obj.name = "Palsaniya";
$obj.data = $input_data;
$serize.push($obj); 

alert(JSON.stringify($serize));