如何避免两个包含相同对象的数组的反射?

时间:2015-07-23 10:01:44

标签: javascript arrays reflection

我有两个相同对象的数组,

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数组的Note值,但我也在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"}];

它是如何反映的,无论如何都要阻止那种反思。

1 个答案:

答案 0 :(得分:0)

您需要克隆对象How do I correctly clone a JavaScript object?

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);