鍍金池/ 問答/Java  網(wǎng)絡(luò)安全  HTML/ js需要把搜索詞組成json格式放入本地緩存,但是現(xiàn)在新增是覆蓋不是追加,求解?

js需要把搜索詞組成json格式放入本地緩存,但是現(xiàn)在新增是覆蓋不是追加,求解?

需求:
把每次搜索的關(guān)鍵詞組成json格式放入localstorage,然后加載這個(gè)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));
        }
    }

clipboard.png

clipboard.png

回答
編輯回答
懷中人

你這段代碼在我本地執(zhí)行時(shí)是正常的,你需要看看是不是哪里有代碼會(huì)自動(dòng)將historyArr置空。

2018年4月10日 01:17
編輯回答
還吻

先讀取原來的數(shù)據(jù),然后和新數(shù)據(jù)拼接在一起再覆蓋不就行了嗎。

2017年12月14日 08:04
編輯回答
撿肥皂

提供給你一個(gè)自己寫的公共方法,以驗(yàn)證。向localStorage中追加內(nèi)容,不覆蓋,且元素stringify后如果相同,則不追加

    appendLocal(key, obj) {
        if(obj == null) return;
        let temp, tempStr = '';
        try {
            if(localStorage.getItem(key) == null) throw new Error('空或undefined')
            temp = JSON.parse(localStorage.getItem(key));
        } catch(err) {
            // 當(dāng)localStorage中沒有對(duì)應(yīng)key,或key對(duì)應(yīng)內(nèi)容為空、undefined,或parse出錯(cuò)時(shí)
            temp = [];
        }
        temp = temp.map((item) => {
            return JSON.stringify(item);
        });
        // 去重
        if(temp.indexOf(JSON.stringify(obj)) === -1) temp.push(JSON.stringify(obj));
        temp.forEach((item, index, arr) => {
            arr.length === index + 1 ? tempStr += `${item}` : tempStr += `${item},`;
        });
        localStorage.setItem(key, `[${tempStr}]`);
    }
2017年7月6日 02:21
編輯回答
逗婦乳

謝邀,每次加載頁面的時(shí)候應(yīng)該整個(gè)讀取出來維護(hù),最好只取一次作為唯一的源頭,每次更新之后整個(gè)保存覆蓋。

或者使用其它庫處理 https://www.npmjs.com/browse/...

2017年12月29日 12:31