最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - What is the difference between .find() and .includes() in JavaScript? - Stack Overflow

programmeradmin2浏览0评论

I am trying to create a method called addTrack with the following functionality:

  • Accepts a track argument
  • Use the track’s id property to check if the current song is in the playlistTracks state
  • If the id is new, add the song to the end of the playlist.

  • Set the new state of the playlist.

What would be the difference if I use the code #1 instead of code #2?

PlaylistTracks is defined in the constructor as following:

playlistTracks: [{ name: 'name1', artist: 'artist1', album: 'album1', id: 1 },
        { name: 'name2', artist: 'artist2', album: 'album2', id: 2 },
      ]

Code #1

addTrack(track){
if (this.state.playlistTracks.includes(this.props.track.id)) {return;}
else {this.state.playlistTracks.push(track);
  this.setState({playlistTracks:this.state.playlistTracks});
}

}

Code #2

addTrack(track) {
if (this.state.playlistTracks.find(savedTrack => savedTrack.id===track.id) {return;}
else {return this.state.playlistTracks.push(track);}
this.setState(playlistTracks:this.state.playlistTracks)}

I am trying to create a method called addTrack with the following functionality:

  • Accepts a track argument
  • Use the track’s id property to check if the current song is in the playlistTracks state
  • If the id is new, add the song to the end of the playlist.

  • Set the new state of the playlist.

What would be the difference if I use the code #1 instead of code #2?

PlaylistTracks is defined in the constructor as following:

playlistTracks: [{ name: 'name1', artist: 'artist1', album: 'album1', id: 1 },
        { name: 'name2', artist: 'artist2', album: 'album2', id: 2 },
      ]

Code #1

addTrack(track){
if (this.state.playlistTracks.includes(this.props.track.id)) {return;}
else {this.state.playlistTracks.push(track);
  this.setState({playlistTracks:this.state.playlistTracks});
}

}

Code #2

addTrack(track) {
if (this.state.playlistTracks.find(savedTrack => savedTrack.id===track.id) {return;}
else {return this.state.playlistTracks.push(track);}
this.setState(playlistTracks:this.state.playlistTracks)}
Share Improve this question edited Feb 22, 2023 at 21:58 Angus 1487 bronze badges asked Jun 10, 2020 at 13:42 B_12B_12 1831 gold badge1 silver badge11 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 17

array.includes will just return true or false if the value is there or not

array.find will find the specific item in the array for you

e.g.

[1,2,3].includes(1) // returns true
[1,2,3].includes(4) // returns false

[1,2,3].find(i => i === 1) // returns 1
[1,2,3].find(i => i === 5) // returns undefined

发布评论

评论列表(0)

  1. 暂无评论