我正在嘗試創建一個變數oldPlayerStats來獲取 的當前值G.playerStats,以便稍后在更新時,我可以從新值中G.playerStats減去以獲得差異。oldPlayerStatsG.playerStats
但是由于某種原因,oldPlayerStats更新始終匹配G.playerStats。
相關代碼如下:
const oldPlayerStats = G.playerStats;
console.log(oldPlayerStats[0].wood); //Is 10 as it should be
//This function affects the value of `G.playerStats`. It does not do anything to oldPlayerStats
cardFunction.function(G, ctx, ctx.currentPlayer, G.opponent, G.attackMultiplier);
console.log(oldPlayerStats[0].wood); //Should be 10, but instead updates to match the new value of `G.playerStats`
uj5u.com熱心網友回復:
現在 oldPlayerStats 只是參考記憶體中的原始物件,這就是它發生變化的原因。
一種選擇是使用結構化克隆來克隆物件以創建深度克隆。
https://developer.mozilla.org/en-US/docs/Web/API/structuredClone
const oldPlayerState = structuredClone(G.playerState)
uj5u.com熱心網友回復:
在 Javascript 中,當您將一個變數賦值給另一個變數時,您是通過參考這樣做的。因此,與其說“我希望 oldPlayerStats 等于 G.playerStats 的值”,不如說 oldPlayerStats 指向存盤 G.playerStats 的記憶體地址。因此,當您更新一個時,它會更新另一個。
您可以使用slice將陣列中的值復制到新陣列中。
IE
oldPlayerStats = G.playerStats.slice()
uj5u.com熱心網友回復:
我遠不是 JS 專家,但在大多數語言中,將復雜的資料結構分配給另一個變數,使用參考——資料沒有被復制,但新變數指向記憶體中的同一個位置。因此,如果你改變了一些原始資料結構的元素,而不是記憶體中的地址,新變數仍然會顯示原始變數的更新值。有幾種方法可以避免它。對于 JavaScript,這應該有所幫助: https ://www.freecodecamp.org/news/how-to-clone-an-array-in-javascript-1d3183468f6a/
uj5u.com熱心網友回復:
盡管提供的答案都是有道理的,并且有許多其他檔案支持這些答案作為可能的解決方案,但它們都不起作用。
最終對我有用的是:
const oldPlayerStats = JSON.parse(JSON.stringify(G.playerStats));
該解決方案來自我發現的以下問題: Uncaught DOMException: Failed to execute 'postMessage on 'Window': An object could not be cloned
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/536626.html
標籤:javascript变量
