簡體   English   中英

改變對象值的不變函數

[英]immutable function that alter object value

var brand = [{id:1,name:'samsung',price:1000},{id:1,name:'lg',price:2000}];
var changed = brand[0].price = 2000;

現在三星的價格等於2000,並且已分配給更改,但是如何在不更改品牌變量的情況下做到呢?

還是我在redux中誤解了不變概念? 上面的代碼實際上還可以嗎?

使用Object#assign創建具有所需更改的新對象。 使用Array#slice獲取原始數組中未更改的項目,並使用Array#concat創建新數組而不是更改原始數組。

 var brand = [{id:1,name:'samsung',price:1000},{id:1,name:'lg',price:2000}]; var index = 0; // changed element index // creates a new object with the merge properties var item = Object.assign({}, brand[index], { price: 2000 }); // creates a new array by combining the elements before the changed item, with the changed item, and the elements after the it in the right order var changed = brand.slice(0, index) // the items before the changed item .concat( item, // the changed item brand.slice(index + 1) // the elements after the changed item ); console.log(changed); console.log(brand); // brand haven't changed 

如果您轉換代碼或瀏覽器兼容性不是問題,則可以使用數組傳播對象傳播語法:

 const brand = [{id:1,name:'samsung',price:1000},{id:1,name:'lg',price:2000}]; const index = 0; // changed element index const changed = [ ...brand.slice(0, index), // the elements before the changed item { ...brand[index], price: 2000 }, // the changed item ...brand.slice(index + 1) // the items after the changed items ]; console.log(changed); console.log(brand); // brand haven't changed 

找到這篇不錯的文章,清楚地說明了我們如何使對象和數組不可變。 http://wecodetheweb.com/2016/02/12/immutable-javascript-using-es6-and-beyond/

暫無
暫無

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

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