![](/img/trans.png)
[英]How can I check if javascript array already contains a specific array
[英]How do I check if a certain array already contains the imdbID and prevent it from adding it again?
每部電影只應添加一次到收藏夾列表,但是此錯誤使它每次我更改頁面並返回到該特定電影頁面並添加時,它都會將自身推入“收藏夾”數組。 如何檢查某個imdbID是否已經存在,並阻止應用將其添加到狀態中?
updateFavorites = movie => {
if (!this.state.favorites.includes(movie)) {
const newFavoriteList = this.state.favorites;
newFavoriteList.push(movie);
this.setState(state => ({
favorites: newFavoriteList
}));
console.log("Added to your favorites.");
} else {
const newFavoriteList = this.state.favorites;
newFavoriteList.splice(newFavoriteList.indexOf(movie), 1);
this.setState(state => ({
favorites: newFavoriteList
}));
console.log("Removed from your favorites.");
}
};
這就是我從收藏夾列表添加和刪除電影的方式。
如評論中所述,您可以使用.find
或.findIndex
進行此比較。 另外,您可以使用.filter
代替.splice
和.indexOf
來刪除影片。 我個人更喜歡這種方法。
updateFavorites = ( movie ) => {
const { favorites } = this.state;
const checkMovie = favorites.find( fav => fav.imdbID === movie.imdbID );
if (!checkMovie) {
return this.setState(
prevState => ( { favorites: [ ...prevState.favorites, movie ] } ) );
}
const newFavoriteList = favorites.filter( fav => fav.imdbID !== movie.imdbID );
this.setState( { favorites: newFavoriteList } );
};
試試這個,對我有用
let checkArray = favorites.every( (item) => {
return item.imdbID !== newItem.imdbID; // newItem is new element for insert
})
if(checkArray) {
//code for insert newItem
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.