如何将JavaScript数组添加到localStorage中以进行临时数据存储?

时间:2019-06-23 19:45:19

标签: javascript

我想将数组数据添加到localStorage中,以便在将数据输入到问题数组中时,刷新网页后,数据应该在那里。实际上,我想推送问题数组并将数据存储到数组中。下面的代码,我已经尝试过,但是不能正常工作。有人可以帮我吗?

//add newly entered data into questions using localStorage.
  if(localStorage.getItem('setQuestions') == null){
    var questions =[];
}else{
    questions =  JSON.parse(localStorage.getItem('setQuestions'));

}

5 个答案:

答案 0 :(得分:0)

首先,我应该说localstorage是一个键值数据库;因此您必须使用JSON.stringify(questions);将对象/数组转换为字符串来对数组进行字符串化;

向本地存储添加字符串非常容易:

localstorage.setItem("questions", JSON.stringify(questions));

但是我建议您使用 WebSQL IndexedDb

答案 1 :(得分:0)

只需将数据添加到数组,然后通过JSON.stringify(questionss)将其放入字符串形式,然后对其进行解析。然后循环遍历以获取值。

if (localStorage.getItem('setQuestions') == null) {
  let questionss = [{
    question: "Why the grass is green?",
    answer: "Because of cholorophyll",
  }, {
    question: "What's the fastest made object on earth?",
    answer: "A man hole cover"
  }];
  localStorage.setItem("setQuestions", JSON.stringify(questionss));

} else {
  let questions = localStorage.getItem('setQuestions');

  JSON.parse(questions).forEach((val, index) =>  alert(val.question + " " + val.answer));
}

选中此js fiddle

答案 2 :(得分:0)

好的。实际上,您没有在刷新浏览器之前向我们展示了数据的存储位置。 您的数据不会自动存储 :) ?

//As soon as you get your question array, do the following
var dataToStore = JSON.stringify(yourArray);
localStorage.setItem('setQuestions', dataToStore);

//And when you're back from movie and wish to continue, then do...
var questions = [];
var storedData = localStorage.getItem('setQuestions');
//Check if it was saved...
if(storedData) {
    questions = JSON.parse(storedData);
}
//You have the same array data that was stored. Now, call your girlfriend and tell her you just won a lotto. 8)
//Additionally, you mentioned `push` somewhere...
//If you need to add new questions to the old one, just do...
var extendedQuestions = questions.concat(newQuestions);/*newQuestions must be an array*/

/*
//add newly entered data into questions using localStorage.
if(localStorage.getItem('setQuestions') == null){
    var questions =[];
}else{
    questions =  JSON.parse(localStorage.getItem('setQuestions'));
}
*/

注意 要求某人为您编写您的代码或为他们编写某人的代码并没有真正的好处。我们应该学会自己做。

答案 3 :(得分:-1)

localstorage可以很容易地在存储之前JSON.stringify接受字符串,并且JSON.parse将该字符串读入数组对象。

答案 4 :(得分:-1)

您只需更改Question函数即可返回这样的对象:

function Question() {
    // everything you wrote here 
    this.render = function () {
        return {options: ..., correct: ...};
    }
}

只需使用由new Question.render()插入的new Question()