使用loop和localStorage保存所有变量[JavaScript]

时间:2016-08-15 10:10:02

标签: javascript save

我想制作一个可以轻松保存所有变量的代码。通常我需要60个变量约120行。不是很有效率。我决定尝试用数组创建一个函数来尝试保存所有变量。它似乎没有用。

我的问题是加载的变量是字符串,但我需要它们是浮点数。

var variablelist = ["numb1","numb2","numb3","numb4","numb5"];
var variablelength = variablelist.length;

function save(){
  for (var i = 0; i < variablelength; i++){
    localStorage[variablelist[i]] = window[variablelist[i]];
  }
}

function load(){
  for (var i = 0; i < variablelength; i++){
    window[variablelist[i]] = localStorage[variablelist[i]];
  }
}

我试过了

window[variablelist[i]] = localStorage[parseFloat(variablelist[i])];

没有任何效果。它仍然是一个字符串。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

首先,看到窗口对象上存储了如此多的东西,这让我很痛苦。你真的应该重新考虑一下!

LocalStorage是一种将键值对存储到浏览器内存以便以后访问的方法。唯一的问题是该值必须是一个字符串。

您可以使用JSON.stringifyJSON.parse函数来解决这个问题:

var objectToSave = {
  key1: 'something',
  key2: 'something else'
};

localStorage.setItem('myObject', JSON.stringify(objectToSave));

console.log(localStorage.getItem('myObject')); // What is stored
console.log(JSON.parse(localStorage.getItem('myObject'))); // The parsed object

否则,如果您已设置保存所有单个变量,那么您就不用太远,只需使用getItemsetItem

var variablelist = ["numb1","numb2","numb3","numb4","numb5"];
var variablelength = variablelist.length;

function save(){
  for (var i = 0; i < variablelength; i++){
    localStorage.setItem(variablelist[i], window[variablelist[i]]);
  }
}

function load(){
  for (var i = 0; i < variablelength; i++){
    window[variablelist[i]] = localStorage.getItem(variablelist[i]);
  }
}

答案 1 :(得分:0)

使用localStore.setItem()localStore.getItem()来存储和加载项目。还可以使用JSON.stringify()JSON.parse()将对象转换为文本,然后将其还原为对象。

var variablelist = ["numb1","numb2","numb3","numb4","numb5"];
var variablelength = variablelist.length;

function save(){
  for (var i = 0; i < variablelength; i++){
    localStorage.setItem(variablelist[i], JSON.stringify(window[variablelist[i]]));
  }
}

function load(){
  for (var i = 0; i < variablelength; i++){
    window[variablelist[i]] = JSON.parse(localStorage.getItem(variablelist[i]));
  }
}