如何在ImmutableJS中更新列表中的列表?

时间:2016-03-06 18:20:30

标签: immutable.js

我在更新ImmutableJS列表中的列表时遇到问题。谁能告诉我我做错了什么?



var rows = Immutable.List();
for (var i = 0; i < 12; i++) {
  rows = rows.push({type:"floor"});
}

var cols = Immutable.List();
for (var j = 0; j < 12; j++) {
  cols = cols.push(rows);
}

var wall = {type:"wall"};

cols = cols.update(cols.get(3).get(4), function(wall) { return wall});

// I expect to get 'wall' written in the console, but the output is 'floor'.
console.log(cols.get(3).get(4).type);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.7.6/immutable.js"></script>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您可以将更新分为两个步骤(请参阅jsfiddle上的示例):

var rows = Immutable.List();
for (var i = 0; i < 12; i++) {
  rows = rows.push({type:"floor"});
}

var cols = Immutable.List();
for (var j = 0; j < 12; j++) {
  cols = cols.push(rows);
}

var wall = {type:"wall"};
var nestedList = cols.get(3);
var newNestedList;
var newCols;
newNestedList = nestedList.update(4, function(item) {return wall});
newCols = cols.update(3, function(list) { return newNestedList});
console.log(newCols.get(3).get(4).type);