[英]What is the difference between Object.assign and JSON.parse(JSON.stringify(obj)) for deep cloning of an object?
[英]Which is the best approach to push an object into an array? - push(obj) or push(JSON.parse(JSON.stringify(obj)))
在我的角度代碼中有一個users: any[] = []
數組,它將用 person 對象動態填充。
someMethod.subscribe((user) => {
this.users.push(user);
})
但是我的一位同事更喜歡以下方法來推動對象
someMethod.subscribe((user) => {
this.users.push(JSON.parse(JSON.stringify(user)));
})
我可以知道 - 哪種方法最好,為什么?
前者。 后者有時用於深度克隆對象,但如果您不修改數組中的對象,則沒有必要。 而且它也有一些風險:你可能會丟失一些 JSON 中沒有的數據,比如函數、正則表達式、符號和未定義; 您最終可能會得到一些更改的數據,例如NaN
變為null
,並且它會根據日期格式弄亂日期。 它也很慢(與實用程序庫中的方法相比):《金融時報》在 2018 年的技術博客上發表了一篇文章,表明在每個請求返回的數據上使用JSON.parse(JSON.stringify(...
會使他們的網站速度減慢10倍。
如果您確實需要在推送對象之前克隆它們,您可以使用像 Lodash 這樣的庫,或者使用push({...user})
,具體取決於您的具體需要。
someMethod.subscribe((user) => {
this.users = [...this.users, user];
});
我想使用第三種方式。 因為短而且看起來很漂亮。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.