Immutable.js - 是否可以在列表的任意位置插入元素?

Immutable.js - is it possible to insert element into list at arbitrary position?

如何在 Immutable.js 列表的任意位置插入元素?

您正在寻找 splicemethod:

Splice returns a new indexed Iterable by replacing a region of this Iterable with new values.

splice(index: number, removeNum: number, ...values: any[])

您可以在其中指定 index,如果您将 0 写为 removeNum,它只会在给定位置插入值:

var list = Immutable.List([1,2,3,4]);
console.log(list.toJS()); //[1, 2, 3, 4]
var inserted = list.splice(2,0,100);
console.log(list.toJS()); //[1, 2, 3, 4]
console.log(inserted.toJS()); //[1, 2, 100, 3, 4] 

演示 JSFiddle.

值得指出的是,您也可以使用insert方法,实际上与list.splice(index, 0, value)同义,但感觉更直观,大大提高了可读性。

const myImmutableList = Immutable.fromJS(['foo', 'baz'])
const newList = myImmutableList.insert(1, 'bar')

console.log(newList.toJS()) //["foo", "bar", "baz"]