我在localStorage中将一组ID设置为“收藏夹”,
var favIndex=$favourites.indexOf($titleId);
if(favIndex==-1){
$favourites.push($titleId);
$('#fav').addClass('favourited');
}
else{
$('#fav').removeClass('favourited');
}
var favouritesJson=JSON.stringify($favourites);
localStorage.setItem('favourites',favouritesJson);
console.log(localStorage.getItem('favourites',favouritesJson));
如果该值尚未在数组中,它将被添加,在else语句中,我需要从数组中删除$ titleId,这可能吗?
最佳答案
使用splice
方法从给定索引中删除n个元素:
if(favIndex==-1){
$favourites.push($titleId);
$('#fav').addClass('favourited');
} else {
$favourites.splice(favIndex, 1);
$('#fav').removeClass('favourited');
}