我有两个相同对象的数组,
var callHistory = [{"CallId":1,"Note":"abcdefghijklmnop"}, {"CallId":2,"Note":"123343"}, {"CallId":3,"Note":"abc123"}];
var tempHistory = [{"CallId":1,"Note":"abcdefghijklmnop"}, {"CallId":2,"Note":"123343"}, {"CallId":3,"Note":"abc123"}];
for(var i = 0; i < tempHistory .length; i++)
{
var callNote = tempHistory [i]["Note"];
if(callNote.length > 6)
{
callNote = callNote.slice(0, 5);
tempHistory [i]["Note"] = callNote;
}
}
这里我正在改变索引0的tempHistory数组的注释值,但我也在callHistory上得到反映的响应。
for循环结束后。
callHistory = [{"CallId":1,"Note":"abcdef"}, {"CallId":2,"Note":"123343"}, {"CallId":3,"Note":"abc123"}];
tempHistory = [{"CallId":1,"Note":"abcdef"}, {"CallId":2,"Note":"123343"}, {"CallId":3,"Note":"abc123"}];
它是如何被反射的,有没有办法阻止这种反射
你需要克隆对象我如何正确克隆一个JavaScript对象?:
function clone(obj) {
if (null == obj || "object" != typeof obj) return obj;
var copy = obj.constructor();
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
}
var callHistory = [{"CallId":1,"Note":"abcdefghijklmnop"}, {"CallId":2,"Note":"123343"}, {"CallId":3,"Note":"abc123"}];
var tempHistory = [{"CallId":1,"Note":"abcdefghijklmnop"}, {"CallId":2,"Note":"123343"}, {"CallId":3,"Note":"abc123"}];
for(var i = 0; i < tempHistory .length; i++)
{
var callNote = clone(tempHistory [i]["Note"]);
if(callNote.length > 6)
{
callNote = callNote.slice(0, 5);
tempHistory [i]["Note"] = callNote;
}
}
console.log(callHistory);
console.log(tempHistory);