Working with array in local storage

2019-07-30 01:21发布

问题:

I am trying to add past searches to local storage and doing that with an array. The problem is that it adds the value two times, even if there is just one call to the function. For every new, distinct search I want it to be added to my array and storage, if there is more than five, the last item is popped.

Called when a search is processed:

SetLocalStorageItem(searchString[1]);

The function that should do it:

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 to clear and display:

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

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

Now, if I clear the searches the array and the storage is empty, and then run the code and searches for "billy", the console.log above prompts:

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

回答1:

You were pushing the localStorage["pastSearches"] to your pastSearches array.
This means you were pushing an array to your array. Basically, you were doing this:

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

While doing this, the old content was also still in the array, so you're duplicating data.

Also, The real problem is that you were using both pastSearches.unshift(search); and pastSearches.push(search);, Adding search to pastSearches twice.

Try this:

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();
        }
    }
}


回答2:

One possible issue is that the parsed array is directly pushed to the pastSearches array every time the SetLocalStorageItem() is called:

if(localStorage["pastSearches"]) {
   pastSearches.push(JSON.parse(localStorage["pastSearches"]));
}

You probably want to do empty the array before adding new elements:

if(localStorage["pastSearches"]) {
   pastSearches = JSON.parse(localStorage["pastSearches"]);
}

and then later add the new element to it:

pastSearches.push(search);

As a side note: in order to empty an array you can simpley set its length to zero. That will prevent creating a new array object:

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