我正在使用React的componentDidUpdate
生命周期方法。
我正在尝试确定两个数组是否相同。
我的prevState
数组如下所示:
prevState.players = [
{
name: 'Wayne Rooney',
age: 31
},
{
name: 'Lionel Messi',
age: 29
},
{
name: 'Robbie Fowler',
age: 42
}
];
并且this.state
数组看起来像这样:
this.state.players = [
{
name: 'Wayne Rooney',
age: 31
},
{
name: 'Lionel Messi',
age: 29
},
{
name: 'Robbie Fowler',
age: 42
}
];
正如您所看到的,如果您展开下面的代码段,它们就不相同:
let playersOne = [{
name: 'Wayne Rooney',
age: 31
},
{
name: 'Lionel Messi',
age: 29
},
{
name: 'Robbie Fowler',
age: 42
}
];
let playersTwo = [{
name: 'Wayne Rooney',
age: 31
},
{
name: 'Lionel Messi',
age: 29
},
{
name: 'Robbie Fowler',
age: 42
}
];
console.log(playersOne == playersTwo)
这是我的反应生命周期代码。
componentDidUpdate(prevProps, prevState) {
if(prevState.players != this.state.players) {
this.updatePlayers(this.state);
}
}
任何人都可以建议确定数组是否相等的最佳方法吗?
答案 0 :(得分:11)
JSON.stringify(playersOne) == JSON.stringify(playersTwo)
答案 1 :(得分:3)
您可以使用array#every
检查两个对象是否具有相同数量的对象,并且每个对象具有相同数量的键和值。
let playersOne = [{ name: 'Wayne Rooney', age: 31 }, { name: 'Lionel Messi', age: 29 }, { name: 'Robbie Fowler', age: 42 } ],
playersTwo = [{ name: 'Wayne Rooney', age: 31 }, { name: 'Lionel Messi', age: 29 }, { name: 'Robbie Fowler', age: 42 } ];
var isSame = playersOne.length === playersTwo.length && playersOne.every((o,i) => Object.keys(o).length === Object.keys(playersTwo[i]).length && Object.keys(o).every(k => o[k] === playersTwo[i][k]));
console.log(isSame);

答案 2 :(得分:2)
您可以使用array.prototype.every
:
var players = [
{
name: 'Wayne Rooney',
age: 31
},
{
name: 'Lionel Messi',
age: 29
},
{
name: 'Robbie Fowler',
age: 42
}
];
var statePlayers = [
{
name: 'Wayne Rooney',
age: 31
},
{
name: 'Lionel Messi',
age: 29
},
{
name: 'Robbie Fowler',
age: 42
}
];
var equals = players.length === statePlayers.length && players.every((e, i) => e.name === statePlayers[i].name && e.age === statePlayers[i].age);
console.log(equals);
答案 3 :(得分:1)