简体   繁体   中英

Javascript localStorage unshift array stops appending after two items

I have a javascript function that fires on page load. My goal is to store a json string in localStorage like this "item1","item2","item3" using the unshift method to build this in an array one item at a time.

This is what my function looks like here:

function storedItems (){
    var modelItem = $('#item').html(),
        modelInt = $('#int').html();

    if (localStorage.modelItem || localStorage.modelInt) {

        var itemStack = [],
            intStack = [],
            itemStorage = localStorage.getItem("modelItem"),
            intStorage = localStorage.getItem("modelInt"),
            itemHistory = JSON.parse(itemStorage),
            intHistory = JSON.parse(intStorage),
            item = JSON.stringify(itemHistory).split(","),
            int = JSON.stringify(intHistory).split(",");
        alert("History " + item + " " + int + " " + item.length + " " + int.length);

        if (item.length > 0) {
            for ( var i = item.length - 1; i >= 0; i--) {
                var obj = item[i],
                    newItem = JSON.parse(obj);

                if(item.length > 1 && item.length < 3) {
                    itemStack.unshift(newItem);
                    itemStack.unshift(modelItem);
                    alert("StringFinder 2 " + modelItem + " " + itemStack);
                } else {
                    newItem.unshift(modelItem);
                    alert("StringFinder 2 " + modelItem + " " + itemStack);
                }
            }
        }
        if (int.length > 0) {
            for ( var i = int.length - 1; i >= 0; i--) {
                var obj = int[i],
                    newInt = JSON.parse(obj);

                if(int.length > 1 && int.length < 3) {
                    intStack.unshift(newInt);
                    intStack.unshift(modelInt);
                    alert("StringFinder 2 " + modelInt + " " + intStack);
                } else {
                    newInt.unshift(modelInt);
                    localStorage.setItem("modelInt", JSON.stringify(newInt));
                    alert("StringFinder 2 " + modelInt + " " + intStack);
                }
            }
        }
        localStorage.setItem("modelItem", JSON.stringify(itemStack));
        localStorage.setItem("modelInt", JSON.stringify(intStack));
        alert("StringFinder 4 " + itemStack + " " + intStack);
    } else {
        localStorage.setItem("modelItem", JSON.stringify(modelItem));
        localStorage.setItem("modelInt", JSON.stringify(modelInt));
    }
}

I can get this result "item1","item2" , but if it fires a third time the script fails after the first History alert fires. I am basically stumped. I have been searching for solutions, and working with some others trying to figure it out without success. Please, help in any way you can.

The cause of the bug you are experiencing is here:

localStorage.setItem("modelItem", JSON.stringify(modelItem));
localStorage.setItem("modelInt", JSON.stringify(modelInt));

You are JSON-encoding and storing string values in your local storage, so when you take them out of local storage and parse them, they are still strings, not arrays.

You need to store them as arrays in the first place:

localStorage.setItem("modelItem", JSON.stringify([modelItem]));
localStorage.setItem("modelInt", JSON.stringify([modelInt]));

I have gotten your code into a working state and you can try it out here:

http://jsfiddle.net/5qad1nwe/1/

For future reference, as I pointed out a few hours ago, if you want a decent answer here, you have to distill your problem to its essence. In many cases, this act of reworking and simplifying the code will often allow you to solve the problem on your own without having to ask.

Here is an example of how you could have asked this question and gotten a quick answer (and possibly upvotes)


I am having trouble storing and retrieving values in localStorage. When they are not yet defined in localStorage, I store the values for the first time (they are just regular string values without much importance), and then the next time I access them from localStorage I want to retrieve them as an array, copy its contents to another array along with another value, and re-store the values:

var modelItem = $('#item').html();

if (localStorage.modelItem ) {
    var itemStack = []
        itemStorage = localStorage.getItem("modelItem"),
        itemHistory = JSON.parse(itemStorage);

    console.log("itemHistory.length is " + itemHistory.length);

    for (var i = 0; i < itemHistory.length; i++) {
        itemStack.unshift(itemHistory[i]);
    }

    itemStack.unshift(modelItem);

    localStorage.setItem("modelItem", JSON.stringify(itemStack));
} else {
    localStorage.setItem("modelItem", JSON.stringify(modelItem));
}

However, the first time I load the data from localStorage, itemHistory.length is not 1 as I expected but actually a larger value. What am I doing wrong?


Here is the solution to my own answer. My apologies for the confusion. I simplified and fixed it here.

var modelItem = $('#item').html();

if (localStorage.modelItem) {
itemStorage = localStorage.getItem("modelItem");
itemHistory = JSON.parse(itemStorage);
alert(itemHistory.length);

if (itemHistory.length > 0) {
    if(itemHistory.length < 3) {
        itemHistory.unshift(modelItem);
        alert("StringFinder 2 " + itemHistory);
    } else {
        itemHistory.unshift(modelItem);
        itemHistory.pop();
        alert("StringFinder 3 " + itemHistory);
    }
}
localStorage.setItem("modelItem", JSON.stringify(itemHistory));
alert("StringFinder 4 " + itemHistory);
} else {
var itemStack = new Array();
itemStack.unshift(modelItem);
localStorage.setItem("modelItem", JSON.stringify(itemStack));
}

Here is the most recent JSFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM