本地存储被覆盖,而不是添加新元素(JavaScript)

我想在本地存储中存储一组对象,但我只能将一个对象存储到该数组中。所有新对象都会覆盖索引 0 中的前一个对象。


这是我的 JavaScript 代码:


class Track {


    constructor (title, genre) {

        this.title    = title;

        this.genre    = genre;        

        this.id       = new Date().getTime();

        this.creation = new Date();

    }

}


class TrackList {


    constructor () {

        this.tracks = [];

    }


    newTrack(track) {

        this.tracks.push(track);

        this.saveLocalStorage();

    }


    saveLocalStorage() {

        localStorage.setItem('tracks', JSON.stringify(this.tracks));

    }

}


const addSongForm = document.querySelector('.addSongForm');



addSongForm.addEventListener('submit', (e) => {

    const songTitle = document.querySelector('.songTitle').value;

    const songGenre = document.querySelector('.songGenre').value;


    const newTrackForm = new Track(songTitle, songGenre);


    const trackList = new TrackList();

    trackList.newTrack(newTrackForm);

});

提前致谢!!


小怪兽爱吃肉
浏览 145回答 1
1回答

catspeake

首先获取本地存储的当前内容,然后将新对象放入数组中。var currentTracks = localStorage.getItem('tracks');localStorage.setItem('tracks', JSON.stringify(JSON.parse(currentTracks).concat(this.tracks)));编辑:如果需要替换与新对象具有相同ID的当前对象,则需要调整新数组。/**&nbsp;* source : https://www.cnblogs.com/water-1/p/10780528.html&nbsp;*/function mergeArray(arr1,arr2){&nbsp; &nbsp; var _arr = new Array();&nbsp; &nbsp; for(var i=0;i<arr1.length;i++){&nbsp; &nbsp; &nbsp; &nbsp;_arr.push(arr1[i]);&nbsp; &nbsp; }&nbsp; &nbsp; for(var i=0;i<arr2.length;i++){&nbsp; &nbsp; &nbsp; &nbsp; var flag = true;&nbsp; &nbsp; &nbsp; &nbsp; for(var j=0;j<arr1.length;j++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(arr2[i]['id']==arr1[j]['id']){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; flag=false;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if(flag){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _arr.push(arr2[i]);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return _arr;}var currentTracks = JSON.parse(localStorage.getItem('tracks'));localStorage.put('tracks', mergeArray(this.tracks, currentTracks));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript