js需要把搜索词组成json格式放入本地缓存,但是现在新增是覆盖不是追加,求解?

需求:

把每次搜索的关键词组成json格式放入localstorage,然后加载这个json做成搜索历史,目前的问题是没一次放入localstorage都是新增覆盖了之前的(如下图),需要的是追加,求解!


// 新增搜索词存放localStorage

    var historyArr=[];

    function addSearchList(){

        var historyObj = {};

        var sInputVal = sInput.val();

        if(sInputVal.length != 0){

            historyObj.search_name = sInputVal;

            historyObj.search_address = 'search-filter.html?search=' + escape(sInputVal);

            console.log(historyArr.length);

            historyArr.push(historyObj);

            localStorage.setItem("searchhistory",JSON.stringify(historyArr));

        }

    }

https://img2.mukewang.com/5c762f9600016a1908000126.jpg

https://img2.mukewang.com/5c762f980001104b08000171.jpg

一只甜甜圈
浏览 635回答 2
2回答

森栏

先读取原来的数据,然后和新数据拼接在一起再覆盖不就行了吗。

MMMHUHU

你这段代码在我本地执行时是正常的,你需要看看是不是哪里有代码会自动将historyArr置空。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript