[英]List of Lists in Immutable.js
I want to have list of lists and push element to it, but I keep getting list with no elements and I can't think of the reason why. 我想拥有列表列表并向其推送元素,但是我一直在获取没有元素的列表,我想不出原因。
I start with 我开始
List([ List([]), List([]) ]);
and I want to have 我想要
List([ List([2,4]), List([3,6]) ]);
The code I have is the following: 我的代码如下:
const { List } = require('immutable')
list = List([ List([]), List([]) ]);
list.get(0).push(2);
list.get(1).push(3);
list.get(0).push(4);
list.get(1).push(6);
console.log(list);
When I run it, it prints out: 当我运行它时,它会打印出来:
List [ List [], List [] ]
There are no elements in the lists. 列表中没有元素。
Of course there will be no elements in the List . 当然, 列表中没有元素。
When you do 当你做
list.get(0).push(2);
You are not mutating the element at the position 0
by pushing 2
into it as you're assuming, you're getting a new List
that is the result of doing that operation, that's the point of Immutable, instead of mutating the original collection you get a fresh new one. 你是不是在位置变异的元素
0
推2
成其为你承担,你得到一个新的List
就是这样做操作的结果,这是不可改变的点,而不是突变的原始集合你换一个新的。
This is how you do what you're trying to do with Immutable: 这是您要对Immutable进行的操作:
const { List } = require('immutable')
list = List([ List([]), List([]) ]);
list = list.set(0, list.get(0).push(2));
list = list.set(1, list.get(1).push(3));
list = list.set(0, list.get(0).push(4));
list = list.set(1, list.get(1).push(6));
console.log(list);
List [ List[2, 4], List[3, 6] ]
列表[List [2,4],List [3,6]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.