This question already has answers here:
Storing Objects in HTML5 localStorage

(22个答案)


5年前关闭。




如何将mycars数组存储在html5的localStorage对象中?
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";

localStorage.mycars=?;

最佳答案

localStorage是针对key : value对的,因此您可能要对数组进行JSON.stringify,并将字符串存储在mycars键中,然后可以将其拉回并对其进行JSON.parse。例如,

var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";

localStorage["mycars"] = JSON.stringify(mycars);

var cars = JSON.parse(localStorage["mycars"]);

09-25 17:47