繁体   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