我有这样的数组:
var myMovie = [];
和这样的对象:
var first = {id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"}
我通过按钮上的
OnClick()
将对象添加到本地存储阵列中。$(document).ready(function() {
$(".btn.btn-outline-success").click(function () {
myMovie.push(first);
localStorage.setItem('myMovie', JSON.stringify(myMovie));
var output = JSON.parse(localStorage.getItem('myMovie'));
将对象添加到本地存储后,本地存储如下所示:
[{id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"}]
我的问题是,如何通过变量名称删除整个对象?我想从
first
删除对象myMovie
。每次对象的索引位置可能不同。[{id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"}, [{id:"tt9574821", title:"Ghost Protocol", year:"2012", type:"Action, Adventure"}]
最佳答案
最好是一个函数,该函数不仅可以更改数组,还可以将其存储在localStorage中。
要找到要删除的正确索引,您可以找到标题正确的对象:
var myMovie=[] //JSON.parse(localStorage.getItem('myMovie')||"[]");
function push(el){
myMovie.push(el);
//localStorage.setItem('myMovie', JSON.stringify(myMovie));
}
function remove(title){
var i=myMovie.findIndex(movie=>movie.title===title);
if(i!==-1){
myMovie.splice(i,1);
//localStorage.setItem('myMovie', JSON.stringify(myMovie));
}
}
push({id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"});
console.log(myMovie);
remove("La La Land");
console.log(myMovie);
为了使运行的stackSnippet,我不得不删除localStorage功能,它被注释掉了。