对对象数组进行排序时出错无法分配为只读对象'[object Array]'的属性'2' [英] Error while sorting array of objects Cannot assign to read only property '2' of object '[object Array]'
本文介绍了对对象数组进行排序时出错无法分配为只读对象'[object Array]'的属性'2'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个对象数组,其中的对象看起来像这样(值改变):
I'm having array of objects where object looks like this (values change):
{
stats: {
hp: 2,
mp: 0,
defence: 4,
agility: 11,
speed: 6,
strength: 31
}
}
我想按速度降序对它们进行排序:
I want to sort them in descending order by speed doing:
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:无法分配为只读对象'[object Array]'的属性'2'
TypeError: Cannot assign to read only property '2' of object '[object Array]'
我想念什么?
Redux存储中的对象数组:
Array of object in redux store:
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
}
},
]
我导入数组并将其分配给变量:
I import the array and assign it to the variable:
let enemies = getState().enemy;
if (enemies) {
//sort by speed stat
enemies.sort((a, b) => {
return b.stats.speed - a.stats.speed
})
}
推荐答案
因为该数组为冻结 >严格模式,则需要先对数组进行复制,然后再对其进行排序:
Because the array is frozen in strict mode, you'll need to copy the array before sorting it:
array = array.slice().sort((a, b) => b.stats.speed - a.stats.speed)
这篇关于对对象数组进行排序时出错无法分配为只读对象'[object Array]'的属性'2'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文