jQuery.grep更改原始数组



jQuery.grep((文档明确指出,进程不会更改grepped数组。

https://api.jquery.com/jquery.grep/

下面的代码从一个原始的、持久的数组arrLibrary中找到一个匹配的值。

然后,我修改生成的commentObj。。。但我对它所做的更改会流回arrLibrary。我想这与GREP的jQuery文档并不矛盾:我们确实创建了一个新数组,一个原始数组的子集,但它仍然引用了原始数组,因此对它所做的更改会流回原始数组?

我错过了什么?如何获取数组的子集,然后更新其中的数据而不破坏原始数据?

var commentObj = [];   //  Will hold the updated object for inserting into page and saving to DB
//  FIRST, find full object from arrLibrary
if (source !== "chrome_logged"){
commentObj = $.grep(arrLibrary, function(commie){ // just use arr
return commie.uniqueID === obj.comment_id;
});
commentObj = commentObj[0];
} else {
commentObj = obj;   //  Just use what was passed
}

稍后在我的代码中,我更新了commentObj.fieldwhatever="this sucks",并且arrLibrary中的匹配键/值更新为匹配。

感谢任何帮助/指导。

这对我来说似乎很疯狂……但我理解。。。即使grep不会更改原始数组(如果匹配,它会生成一个子集(,生成的数据子集仍然引用原始数组。

因此,如果更新生成的数组,原始数组也会发生变化。

所以我做了一个深度复制来打破与原作的联系。。。

var commentObj1 = [];   //  temp array - subset of arrLibrary...will still be connected to arrLibrary - reference
//  FIRST, find full object from arrLibrary
if (source !== "chrome_logged"){
commentObj1 = $.grep(arrLibrary, function(commie){ // just use arr
return commie.uniqueID === obj.comment_id;
});
commentObj1 = commentObj1[0];
} else {
commentObj1 = obj;   //  Just use what was passed
}
var commentObj = $.extend(true, {}, commentObj1); // deep copy - break reference to arrLibrary

最新更新