簡體   English   中英

設置時間確實會影響對象

[英]Set Hours does affect the Object

我目前面臨一個奇怪的問題,由於我不了解,我想討論一下。

我有以下示例代碼:

 const created_at = new Date(); var myObj = { "key": "value", "expires_in": 36000 }; Object.assign(myObj, { created_at: created_at}); var expiresInHours = Math.floor(myObj.expires_in / (60 * 60)); console.log(myObj); var expires_at = created_at.setHours(created_at.getHours() + expiresInHours); console.log(myObj); expires_at = new Date(expires_at); Object.assign(myObj, { expires_at: expires_at }); console.log(myObj); 

似乎created_at.setHours所在的行確實影響了我的對象。 為什么價值myObj.created_at一樣myObj.expires_at執行后.setHours功能,我如何才能解決這個問題?

根據MDN上的文檔

setHours()方法根據本地時間設置指定日期的小時數,並返回自1970年1月1日00:00:00 UTC到更新的Date實例表示的時間以來的毫秒數。

它明確說明了其行為遵循觀察方式的原因。

如果只想更改expires_at ,則必須復制created_at ,然后對其進行更新。

 const created_at = new Date(); var myObj = { "key": "value", "expires_in": 36000 }; Object.assign(myObj, { created_at: created_at }); var expiresInHours = Math.floor(myObj.expires_in / (60 * 60)); console.log(myObj); /// Copy and update var expires_at = new Date(created_at).setHours(created_at.getHours() + expiresInHours); console.log(myObj); expires_at = new Date(expires_at); Object.assign(myObj, { expires_at: expires_at }); console.log(myObj); 

編輯這似乎對JavaScript常量感到困惑。 再次從文檔

const聲明創建對值的只讀引用。 並不意味着它擁有的價值是不變的,只是該變量標識符不能被重新分配。 例如,在內容是對象的情況下,這意味着可以更改對象的內容(例如,其屬性)。

因此,雖然不能更改const來引用其他值,但是可以更新該值屬性。

setHours()修改其調用日期,然后返回修改后的對象的getTime()。 我認為您只需要刪除任務即可...

var expires_at = expires_at.setHours(created_at.getHours()+ expiresInHours);

當您編寫此行時:

Object.assign(myObj, { created_at: created_at});

created_at變量是Compound。 復合值是參考傳遞。 因此,當created_at.setHours ,它將更改myObj對象中鍵created_at

為了解決您的問題,您可以使用以下簡單代碼進行更改:

//Object.assign(myObj, { created_at: created_at});
Object.assign(myObj, { created_at: new Date()});

暫無
暫無

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

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