我正在使用以下函数向每个数组对象添加索引,但是当我检查console.log时,所有id都会获得相同的值
var foo = [...this.props.articleList];
foo.forEach(function(row, index) {
row.id = index+1;
});
console.log(foo);
我想要这样的东西=>
[{…}, {…}, {…}, {…}, id: 1], [{…}, {…},
{…}, {…}, id: 2], [{…}, {…}, {…}, {…}, id: 3]
但它回来了
[{…}, {…}, {…}, {…}, id: 3], [{…}, {…}, {…}, {…}, id:
3], [{…}, {…}, {…}, {…}, id: 3]
解决方法:
该问题似乎源于处理foo并随后以可变方式处理row.id.
解决方案是利用通常称为克隆的策略.
诸如spread syntax和Array.prototype.map()之类的工具通常对此有用.
请参见下面的实际示例.
case types.SOMETHING:
return {...state, List: [...state.List, action.payload].map((row, index) => ({...row, index}))}