排序对象数组时出错,无法将对象“[ object Array ]”的只读属性“2”赋值给“[ object Array ]”

我有一个对象数组,其中的对象如下所示(值变化) :

   {
stats: {
hp: 2,
mp: 0,
defence: 4,
agility: 11,
speed: 6,
strength: 31
}
}

我想把它们按速度降序排列:

  array.sort((a, b) => {
return b.stats.speed - a.stats.speed
})

However I'm getting this error and I can't really decipher whats going on:

TypeError: Cannot assign to read only property '2' of object '[object Array]'

我错过了什么?

编辑: 返回存储中的对象数组:

const enemyDefaultState = [
{
name: 'European Boy1',
stats: {
hp: 2,
mp: 0,
defence: 4,
agility: 11,
speed: 6,
strength: 31
}
},
{
name: 'European Boy2',
stats: {
hp: 2,
mp: 0,
defence: 4,
agility: 4,
speed: 2,
strength: 31
}
},
{
name: 'European Boy3',
stats: {
hp: 2,
mp: 0,
defence: 4,
agility: 7,
speed: 7,
strength: 31
}
},

]

我导入数组并将其赋给变量:

 let enemies = getState().enemy;
if (enemies) {
//sort by speed stat
enemies.sort((a, b) => {
return b.stats.speed - a.stats.speed
})
}
83886 次浏览

Because the array is 冻僵了 in 严格模式, you'll need to copy the array before sorting it:

array = array.slice().sort((a, b) => b.stats.speed - a.stats.speed)

帕特里克所说的原因是数组被冻结了。所以任何复制数组的方法都可以像他建议的那样工作。

array = array.slice().sort((a, b) => b.stats.speed - a.stats.speed)

I just want to add that the 原因 the array is frozen in your case is because your using the array as props from the redux store and props in React are immutable hence your not being able to mutate the array.

这个数组被冻结以防止 redux 状态的变异。您可以使用 response cloneElement () : https://reactjs.org/docs/react-api.html#cloneelement

[...enemies].sort((a, b) => {
return b.stats.speed - a.stats.speed
})

需要说明的是,问题不仅仅是数组被冻结了。可以对冻结的数组进行迭代。正如在 ReactJS 排序-TypeError: 0是只读的中指出的,问题在于 Array.sort就地对数组进行排序,这意味着它试图改变数组。这就是为什么需要向它传递数组的一个可变副本。