我是一名新的jquery学习者。我有一个问题。
我写了这个脚本,但结果不正确。
var details = <?php echo json_encode($all_data["holiday"]);?>;
var myArray = details.split("|");
var a = {};
var natDays = [];
for(var i=0;i<myArray.length;i++){
var ex_array = myArray[i].split(",");
a["month"] = ex_array[0];
a["date"] = ex_array[1];
a["name"] = ex_array[2];
natDays.push(a);
}
alert( JSON.stringify(natDays) );
我在警告中收到以下错误结果:
[
{"month":"3","date":"7","name":"test"},
{"month":"3","date":"7","name":"test"},
{"month":"3","date":"7","name":"test"},
{"month":"3","date":"7","name":"test"}
]
应该是:
[
{"month":"4","date":"11","name":"test"},
{"month":"4","date":"4","name":"test"},
{"month":"4","date":"13","name":"song kran festival"},
{"month":"3","date":"7","name":"test"}
]
我该怎么办?请指教。
答案 0 :(得分:1)
问题是你在循环的每一步推送对同一对象(存储在a
)的引用 - 如a['month']
等等。你只是扩充现有对象,而不是创建一个新的。
要解决此问题,请使用a
符号直接删除此object literal
变量并在每个步骤创建一个新对象:
for (var i=0; i < myArray.length; i++){
var ex_array = myArray[i].split(",");
natDays.push({
month: ex_array[0],
date: ex_array[1],
name: ex_array[2]
});
}
您可以使用jQuery.map():
使此代码更简洁var natDays = $.map(myArray, function(rec) {
var fields = rec.split(',');
return {
month: fields[0],
date: fields[1],
name: fields[2]
};
});
答案 1 :(得分:0)
创建a
INSIDE the loop
....
for(var i=0;i<myArray.length;i++){
var a = {};
^^^^^^^^^^^ here
var ex_array = myArray[i].split(",");