有人可以解释其中的区别.
Could someone explain the difference.
谢谢
推荐答案在此示例中,
var a = {address: {postcode: 5085}} var d = Immutable.Map(a);在这里, d.get('address')是不可变的.它的值不能更改为任何其他对象.我们只能使用ImmutableJS的Immutable.Map.set()函数从现有对象创建一个新对象.
Here, d.get('address') is immutable. It's value cannot change to any other objects. We can only create a new Object from the existing object using the Immutable.Map.set() function of ImmutableJS.
但是,d.get('address')引用的对象(即{postcode:5085})是标准的JavaScript对象.它是可变的.这样的语句可以更改postcode的值:
But, the object referenced by d.get('address') i.e, {postcode:5085} is a standard JavaScript object. It is mutable. A statement like this can alter the value of postcode:
d.get('address').postcode=6000;如果再次检查d的值,则可以看到他的值已更改.
If you check the value of d again, you can see that he value has been changed.
console.log(JSON.stringify(d)); //Outputs {"address":{"postcode":6000}}这违反了不变性原则.
which is against the principles of immutability.
原因是像List和Map这样的ImmutableJS数据结构将不可变性功能仅赋予List/Map的1级成员.
The reason is that ImmutableJS data structures like List and Map imparts the immutability feature to only the level-1 members of the List/Map.
因此,如果您在数组内有对象或对象内的数组又希望它们也是不可变的,则选择Immutable.fromJS .
So, if you have objects inside arrays or arrays inside objects and want them too to be immutable, your choice is Immutable.fromJS.
var a = {address: {postcode: 5085}} var b = Immutable.fromJS(a); b.get('address').postcode=6000; console.log(JSON.stringify(b)); //Outputs {"address":{"postcode":5085}}从上面的示例中,您可以清楚地了解fromJS如何使嵌套成员不可变.
From the above example you can clearly know how fromJS makes the nested members immutable.
我希望您了解Map和fromJS之间的区别.一切顺利=)
I hope you understood the difference between Map and fromJS. All the best =)
更多推荐
ImmutableJS Map()和fromJS()有什么区别?
发布评论