最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Arrays and objects in localstorage not working - Stack Overflow

programmeradmin4浏览0评论

I am working on a TODO list, I'm trying to make this work with local storage. But there is a problem in my code I can't resolve.

The function getTaskArray() retrieved the, whats meant to be, array from the local storage under the key 'tasks'. If it cannot find it it created a new array instead.

The pushData() function should push the task object into the array. But I get the following error: taskArray.push is not a function.

I've attached a snippet of my code below.

Thanks in advance for your help!

var taskArray;
function getTaskArray() {
    var taskArrayString = localStorage.getItem("tasks");
    if (taskArrayString !== null && typeof taskArrayString === "string") {
        taskArray = taskArrayString;
        console.log("Succesfully retrieved 'tasks' and contents.");
    } else {
        console.log("Succesfully retrieved 'tasks', contents were not a string or held no contents. Contents of 'tasks' reset to empty array");
        var emptyArray = JSON.stringify(new Array());
        localStorage.setItem("tasks", emptyArray);
        taskArray = localStorage.getItem("tasks");
    };
};

var taskString;

function pushData() {
    taskString = JSON.stringify(taskObject);
    taskArray = taskArray.push(taskString);
};

Update:

The plete version of my code:

// All functions
var taskFromHtml;
var priorityFromHtml;

function getTaskInput() {
    try {
        taskFromHtml = $("#taak").val();
        priorityFromHtml = $("#prioriteit").val();
        console.log("Succesfully retrieved data. Task: " + taskFromHtml + ". Priority: " + priorityFromHtml + ".");
    } catch(e) {
        console.log("Failed to retrieve data, unexpecter error.");
    };
};

var taskObject;
function taskToObject() {
    taskObject = {
        task: taskFromHtml,
        priority: priorityFromHtml,
        finished: false
    }; 
};

var taskArray;
function getTaskArray() {
    var taskArrayString = localStorage.getItem("tasks");
    if (taskArrayString !== null && typeof taskArrayString === "string") {
        taskArray = JSON.parse(taskArrayString); // <------
        console.log("Succesfully retrieved 'tasks' and contents.");
    } else {
        console.log("Succesfully retrieved 'tasks', contents were not a string or held no contents. Contents of 'tasks' reset to empty array");
        var emptyArray = JSON.stringify(new Array());
        localStorage.setItem("tasks", emptyArray);
        taskArray = localStorage.getItem("tasks");
        taskArray = JSON.parse(taskArray); // <------
    };
};

var taskString;

function pushData() {
    taskString = JSON.stringify(taskObject);
    taskArray = taskArray.push(taskString);
};

And it's HTML:

  <form id="todoInsert" action="#">
        <input type="text" name="task" id="taak">
        <select id="prioriteit">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
        </select>

        <input type="submit" id="formSubmit">
    </form>
    <div id="addItem">+</div>

I am working on a TODO list, I'm trying to make this work with local storage. But there is a problem in my code I can't resolve.

The function getTaskArray() retrieved the, whats meant to be, array from the local storage under the key 'tasks'. If it cannot find it it created a new array instead.

The pushData() function should push the task object into the array. But I get the following error: taskArray.push is not a function.

I've attached a snippet of my code below.

Thanks in advance for your help!

var taskArray;
function getTaskArray() {
    var taskArrayString = localStorage.getItem("tasks");
    if (taskArrayString !== null && typeof taskArrayString === "string") {
        taskArray = taskArrayString;
        console.log("Succesfully retrieved 'tasks' and contents.");
    } else {
        console.log("Succesfully retrieved 'tasks', contents were not a string or held no contents. Contents of 'tasks' reset to empty array");
        var emptyArray = JSON.stringify(new Array());
        localStorage.setItem("tasks", emptyArray);
        taskArray = localStorage.getItem("tasks");
    };
};

var taskString;

function pushData() {
    taskString = JSON.stringify(taskObject);
    taskArray = taskArray.push(taskString);
};

Update:

The plete version of my code:

// All functions
var taskFromHtml;
var priorityFromHtml;

function getTaskInput() {
    try {
        taskFromHtml = $("#taak").val();
        priorityFromHtml = $("#prioriteit").val();
        console.log("Succesfully retrieved data. Task: " + taskFromHtml + ". Priority: " + priorityFromHtml + ".");
    } catch(e) {
        console.log("Failed to retrieve data, unexpecter error.");
    };
};

var taskObject;
function taskToObject() {
    taskObject = {
        task: taskFromHtml,
        priority: priorityFromHtml,
        finished: false
    }; 
};

var taskArray;
function getTaskArray() {
    var taskArrayString = localStorage.getItem("tasks");
    if (taskArrayString !== null && typeof taskArrayString === "string") {
        taskArray = JSON.parse(taskArrayString); // <------
        console.log("Succesfully retrieved 'tasks' and contents.");
    } else {
        console.log("Succesfully retrieved 'tasks', contents were not a string or held no contents. Contents of 'tasks' reset to empty array");
        var emptyArray = JSON.stringify(new Array());
        localStorage.setItem("tasks", emptyArray);
        taskArray = localStorage.getItem("tasks");
        taskArray = JSON.parse(taskArray); // <------
    };
};

var taskString;

function pushData() {
    taskString = JSON.stringify(taskObject);
    taskArray = taskArray.push(taskString);
};

And it's HTML:

  <form id="todoInsert" action="#">
        <input type="text" name="task" id="taak">
        <select id="prioriteit">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
        </select>

        <input type="submit" id="formSubmit">
    </form>
    <div id="addItem">+</div>
Share Improve this question edited Nov 19, 2015 at 9:22 Demiën Drost asked Nov 19, 2015 at 8:52 Demiën DrostDemiën Drost 1731 gold badge3 silver badges14 bronze badges 4
  • Where's taskObject defined? – hindmost Commented Nov 19, 2015 at 8:55
  • @BasvanStein it is a little further in the code, have not yet started debugging that. But there is a line of code in the snippet above: localStorage.setItem("tasks", []); – Demiën Drost Commented Nov 19, 2015 at 9:02
  • @DemiënDrost ok, be sure to do JSON.stringify when setting the localStorage as well, see my updated answer for your fixed code. – Niki van Stein Commented Nov 19, 2015 at 9:16
  • @hindmost var taskObject; function taskToObject() { taskObject = { task: taskFromHtml, priority: priorityFromHtml, finished: false }; }; – Demiën Drost Commented Nov 19, 2015 at 9:16
Add a ment  | 

2 Answers 2

Reset to default 5

You get the error because you try to perform the push function on a String instead of an array.

When you get the String from the localStorage you need to parse it using JSON.parse().

taskArray = JSON.parse( localStorage.getItem("tasks"));

And also when your receive is succesfully in the if part:

taskArray = JSON.parse(taskArrayString);

Your plete working code would be:

var taskArray;
function getTaskArray() {
    var taskArrayString = localStorage.getItem("tasks");
    if (taskArrayString !== null && typeof taskArrayString === "string") {
        taskArray = JSON.parse(taskArrayString); // <------
        console.log("Succesfully retrieved 'tasks' and contents.");
    } else {
        console.log("Succesfully retrieved 'tasks', contents were not a string or held no contents. Contents of 'tasks' reset to empty array");
        var emptyArray = JSON.stringify(new Array());
        localStorage.setItem("tasks", emptyArray);
        taskArray = localStorage.getItem("tasks");
        taskArray = JSON.parse(taskArray); // <------
    };
};

var taskString;

function pushData() {
    taskString = JSON.stringify(taskObject);
    taskArray.push(taskString); // <----- !No need to assign there.
};

Here you can see a working JsFiddle: https://jsfiddle/txvp9uwc/2/

You can only save the data in string format in the local storage. You can not save, dates, numbers or any other data types. For that you can serialize and deserialize your data as JSON string and then persist the data.

There are some awesome wrapper libraries available which do that for you: https://github./nbubna/store or https://github./marcuswestin/store.js/

Update

You need to deserialize your string after retrieval before using it:

var taskArrayString = localStorage.getItem("tasks");
if (taskArrayString !== null && typeof taskArrayString === "string") {
    taskArray = JSON.parse(taskArrayString);   // deserializing here
    console.log("Succesfully retrieved 'tasks' and contents.");
}
发布评论

评论列表(0)

  1. 暂无评论