我有对象数组,其中对象如下所示(值发生变化):
{
stats: {
hp: 2,
mp: 0,
defence: 4,
agility: 11,
speed: 6,
strength: 31
}
}
我想按执行速度降序对它们进行排序:
array.sort((a, b) => {
return b.stats.speed - a.stats.speed
})
但是我收到此错误,并且我无法真正破译发生了什么:
类型错误:无法分配给对象“[object Array]”的只读属性“2”
我错过了什么?
编辑: redux 存储中的对象数组:
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
})
}
请您参考如下方法:
因为数组是frozen在 strict mode ,您需要在排序之前复制数组:
array = array.slice().sort((a, b) => b.stats.speed - a.stats.speed)