check if two arrays contain identical objects - react componentDidUpdate
本问题已经有最佳答案,请猛点这里访问。
我使用的是React的
我试图确定两个数组是否相同。
我的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | prevState.players = [ { name: 'Wayne Rooney', age: 31 }, { name: 'Lionel Messi', age: 29 }, { name: 'Robbie Fowler', age: 42 } ]; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | this.state.players = [ { name: 'Wayne Rooney', age: 31 }, { name: 'Lionel Messi', age: 29 }, { name: 'Robbie Fowler', age: 42 } ]; |
如您所见,如果展开下面的代码段,它们将不相等:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | 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) |
这里是我的反应生命周期代码。
1 2 3 4 5 | componentDidUpdate(prevProps, prevState) { if(prevState.players != this.state.players) { this.updatePlayers(this.state); } } |
有人能就确定数组是否相等的最佳方法提出建议吗?
您可以使用
1 2 3 4 | 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); |
您可以使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | 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); |