javascript localstorage - 保存数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22991871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:09:42  来源:igfitidea点击:

localstorage - save array

javascripthtmllocal-storage

提问by benjipelletier

I have localstorage working to where I can save inputs and push them to a list. Now I would like to save the list in localstorage because when I reload the list resets because of var fav = new Array();is defined at the start in this jsFiddle. How can I work around this?

我有 localstorage 可以保存输入并将它们推送到列表中。现在我想将列表保存在 localstorage 中,因为当我重新加载列表时,因为var fav = new Array();在此jsFiddle的开头定义了。我该如何解决这个问题?

Thanks, Ben

谢谢,本

回答by Arthur

It's realy easy, you just need to use JSON data to save it :

这真的很简单,你只需要使用 JSON 数据来保存它:

// Save
var datas = ["1", "2", "3"];
localStorage["datas"] = JSON.stringify(datas);

// Retrieve
var stored_datas = JSON.parse(localStorage["datas"]);

回答by Mac

This is simple to do with localDataStorage, where you can transparently set/get any of the following "types": Array, Boolean, Date, Float, Integer, Null, Object or String.

这对于localDataStorage很简单,您可以在其中透明地设置/获取以下任何“类型”:数组、布尔值、日期、浮点数、整数、空值、对象或字符串。

[DISCLAIMER] I am the author of the utility [/DISCLAIMER]

[免责声明] 我是该实用程序的作者 [/免责声明]

Examples:

例子:

localDataStorage.set( 'key1', 'Belgian' );
localDataStorage.set( 'key2', 1200.0047 );
localDataStorage.set( 'key3', true );
localDataStorage.set( 'key4', { 'RSK' : [1,'3',5,'7',9] } );
localDataStorage.set( 'key5', null );

localDataStorage.get( 'key1' );   -->   'Belgian'
localDataStorage.get( 'key2' );   -->   1200.0047
localDataStorage.get( 'key3' );   -->   true
localDataStorage.get( 'key4' );   -->   Object {RSK: Array(5)}
localDataStorage.get( 'key5' );   -->   null

As you can see, the primitive values are respected. In your case, we would do this:

如您所见,原始值受到尊重。在您的情况下,我们会这样做:

>localDataStorage.set( 'datas', ["1", "2", "3"] );

Note that we didn't need to do any stringification to our key value. You can specify it plainly and clearly. Now, when we retrieve it...

请注意,我们不需要对键值进行任何字符串化。您可以清楚明确地指定它。现在,当我们检索它时...

>localDataStorage.get( 'datas' ) -->

... we will get:

... 我们将获得:

>(3) ["1", "2", "3"] 

exactly what we started with, without having to convert anything.

正是我们开始的,无需转换任何东西。

回答by Matas Vaitkevicius

If you want to prevent your variable from being reset try this, if you want to reload page and keep old value this is not gonna help thought.

如果你想防止你的变量被重置试试这个,如果你想重新加载页面并保留旧值,这无济于事。

  if (typeof fav === 'undefined'){
        var fav = new Array();}