簡體   English   中英

jQuery.grep 更改原始數組

[英]jQuery.grep changes original array

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 =“這很糟糕”,並且 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM