推送阵列;将多个值存储到一个键中

时间:2016-08-01 08:48:51

标签: javascript local-storage

我试图将多个值(标题)存储到一个键中。我首先提示用户输入他们的标题,然后将其保存到标题'。但是当我输入多个值时,只有一个值附加到键“标题”上。此外,它说titles.push不是一个功能。

//get the title from user
var title = prompt("What would you like your title to be?");
localStorage.setItem(title, editElem.innerHTML); 

//save the editor contents to local storage based on title
document.getElementById("update").innerHTML = "Edits saved!";
var theDiv = document.getElementById("Contentable");
var content = document.createTextNode(title);
theDiv.appendChild(content);
var br = document.createElement("br");
theDiv.appendChild(br);

//save the all titles in array so you know what documents exist
var titles = localStorage.getItem("titles");
if(titles == null) 
    titles = new Array();
if(titles.indexOf(title) < 0) 
    titles.push(title); 
localStorage.setItem("titles", titles); 

1 个答案:

答案 0 :(得分:0)

使用以下对象将标题推送到存储。请注意JSON.stringify如何从Array转换为string,以及JSON.parse如何做出相反的反应。

var titlesStore =
        {
            Count: function () {
                var stack = JSON.parse(localStorage.getItem("titles"));
                if (!stack)
                    return 0;
                return stack.length;
            },
            Peek: function () {
                var stack = JSON.parse(localStorage.getItem("title"));
                if (!stack)
                    stack = [];
                if (stack.length > 0)
                    return stack.pop();
            },
            Push: function (token) {
                var stack = JSON.parse(localStorage.getItem("titles"));
                if (!stack)
                    stack = [];
                stack.push(token);
                localStorage.setItem("title", JSON.stringify(stack));
            },
            // more methods to you might wish to implement: search, insert, etc.
        }

    // usage:
    titlesStore.Push("new title"); // sets the last title
    titlesStore.Peek(); // gets the last title ;