我试图将过去的搜索添加到本地存储中,并使用数组来完成。问题在于,即使对该函数只有一次调用,它也会将值相加两次。对于每个新的,不同的搜索,我希望将其添加到我的阵列和存储中,如果超过五个,则弹出最后一项。

在处理搜索时调用:

SetLocalStorageItem(searchString[1]);


应该执行的功能:

function SetLocalStorageItem(search) {
    if(search === '') {
        return;
    }
    console.log(localStorage);

    // Check if the browser support Local Storage
    if(localStorage) {
        if(localStorage["pastSearches"]) {
            pastSearches.push(JSON.parse(localStorage["pastSearches"]));
        }
        // Check if the value exists in the array,
        // returns -1 if the array does not contain the value
        if($.inArray(search, pastSearches) == -1) {
            // If not, put it first and...
            pastSearches.unshift(search);
            //  ...pop one at the end if array is too big
            if(pastSearches.length > 5) {
                pastSearches.pop();
            }
            pastSearches.push(search);

            // Adding the search to the storage
            localStorage["pastSearches"] = JSON.stringify(pastSearches);
            DisplayPastSearches();
        }
    }
}


清除和显示功能:

function ClearSearches() {
    // If there is any past searches
    localStorage.clear();
    pastSearches = [];
}

function DisplayPastSearches() {
    if(pastSearches.length) {
        $("<div>" + pastSearches + "</div>").appendTo(".container");
    }
}


现在,如果清除搜索数组并且存储空间为空,然后运行代码并搜索“ billy”,则上面的console.log会提示:

Storage
length: 1
pastSearches: "["billy","billy"]"
__proto__: Storage

最佳答案

您正在将localStorage["pastSearches"]推送到您的pastSearches数组。
这意味着您正在将阵列推入阵列。基本上,您正在这样做:

var a = [1,2],
    b = [3,4];
a.push(b);
// a == [1, 2, [3, 4]]


在执行此操作时,旧内容也仍在数组中,因此您正在复制数据。

另外,真正的问题是您同时使用了pastSearches.unshift(search);pastSearches.push(search);,两次将search添加到pastSearches

尝试这个:

function SetLocalStorageItem(search) {
    if(search === '') {
        return;
    }
    console.log(localStorage);

    // Check if the browser support Local Storage
    if(localStorage) {
        if(localStorage["pastSearches"]) {
            pastSearches = JSON.parse(localStorage["pastSearches"]);
        }
        // Check if the value exists in the array,
        // returns -1 if the array does not contain the value
        if(pastSearches.indexOf(search) == -1) { // Also, no need to use jQuery here.
            // If not, put it first and...
            pastSearches.unshift(search);
            //  ...pop one at the end if array is too big
            if(pastSearches.length > 5) {
                pastSearches.pop();
            }
            // pastSearches.push(search); <-- would you look at that, you're adding search to the array twice.

            // Adding the search to the storage
            localStorage["pastSearches"] = JSON.stringify(pastSearches);
            DisplayPastSearches();
        }
    }
}

10-06 08:28