简体   繁体   English

Javascript localStorage unshift数组在两项之后停止追加

[英]Javascript localStorage unshift array stops appending after two items

I have a javascript function that fires on page load. 我有一个在页面加载时触发的javascript函数。 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. 我的目标是使用unshift方法将一个json字符串像这样的"item1","item2","item3"一样存储在localStorage中"item1","item2","item3"将其构建在一个数组中。

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. 我可以得到此结果"item1","item2" ,但是如果它第三次触发,则脚本在第一个历史记录警报触发后失败。 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. 您使用JSON编码并将字符串值存储在本地存储中,因此当您将它们从本地存储中取出并解析它们时,它们仍然是字符串,而不是数组。

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/ 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. 我在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: 当它们尚未在localStorage中定义时,我会第一次存储这些值(它们只是常规字符串值,没有太大的意义),然后下次我从localStorage访问它们时,我想将它们作为数组检索,将内容与另一个值一起存储到另一个数组,然后重新存储这些值:

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. 但是,当我第一次从localStorage加载数据时, itemHistory.length不是我预期的1,而是一个更大的值。 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 这是最新的JSFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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