繁体   English   中英

在localstorage中存储键值数组

[英]Storing key values array in localstorage

我正在尝试使用以下代码将数组存储在localstorage中:

var tempval = [];
tempval['key'] = 1;                    
localStorage.setItem("Message", JSON.stringify(tempval));

但在localstorage中它只显示[]

那么如何存储它以及我在哪里做错了?

这是你的代码: -

var tempval ={};
tempval.key = 1;                    
localStorage.setItem("Message", JSON.stringify(tempval));

JavaScript不支持具有命名索引的数组.Arrays总是在javascript中使用编号索引。 如果您想使用命名索引,请使用对象。

使用数组 (编号索引)

var tempval = [];
tempval[0] = 1;

使用对象 (命名索引)

 var tempval = {};
 tempval['key'] = 1;

使用var tempval ={}; 而不是var tempval = [];

所以你的问题对我来说并不是那么清楚,但我试图给你一个在本地存储中存储多维数组的通用解决方案,

    var a= [[1,2,3],["hello","world"]]; // multi dimentional array 
    console.log(a);
    var b = JSON.stringify(a); // converting the array into a string 
    console.log(b);
    localStorage.setItem("TestData",b); // storing the string in localstorage
    var c= JSON.parse(localStorage.getItem("TestData")); //accessing the data from localstorgae.
    console.log(c);

这是在Jsbin中运行的代码

这个问题已经回答了(重复):

https://stackoverflow.com/a/3357615/10387837

简短的回答是localStorage.setItem仅支持字符串作为参数。 为了将它与数组一起使用,建议使用JSON.stringify()传递参数和JSON.parse()来获取数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM