是否可以像在 Javascript 对象中一样在 localStorage 中存储整数值并在不进行类型转换的情况下提取它?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33952287/
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 17:04:11  来源:igfitidea点击:

Is it possible to store integer value in localStorage like in Javascript objects and extract it without typecasting?

javascripthtmllocal-storage

提问by nickalchemist

When I assign integer value to localStorage item

当我为 localStorage 项目分配整数值时

localStorage.setItem('a',1)

and check its type

并检查其类型

typeof(localStorage.a)
"string"

it returns string, I can typecast it to intfor my use

它返回string,我可以将它类型转换为int供我使用

parseInt(localStorage.a)

My question is it possible to store integer value inside localStorage as I can do for Javascript objects without typecasting?

我的问题是可以在 localStorage 中存储整数值,就像我可以在没有类型转换的情况下为 Javascript 对象做的那样吗?

a={};
a.number=1;
typeof(a.number)
"number"

采纳答案by Adam Zerner

My question is it possible to store integer value inside localStorage as I can do for Javascript objects without typecasting?

我的问题是可以在 localStorage 中存储整数值,就像我可以在没有类型转换的情况下为 Javascript 对象做的那样吗?

No.

不。

Storage objects are simple key-value stores, similar to objects, but they stay intact through page loads. The keys can be strings or integers, but the values are always strings. [source]

存储对象是简单的键值存储,类似于对象,但它们在页面加载时保持完整。键可以是字符串或整数,但值始终是字符串[来源]

回答by Kaiido

Actually you can, if we agree that parsing is not the same as typecasting :

实际上你可以,如果我们同意解析与类型转换不同:

let val = 42;
localStorage.answer = JSON.stringify(val);
let saved = JSON.parse(localStorage.answer);
console.log( saved === val ); // true

Fiddlesince over-protected stacksnippets don't allow localStorage.

Fiddle因为过度保护的 stacksnippets 不允许 localStorage。

For simplicity, you should anyway always stringify to JSON what you are saving in localStorage, this way you don't have to think about what you are saving / retrieving, and you will avoid "[object Object]"being saved.

为简单起见,您无论如何都应该始终将您在 localStorage 中保存的内容字符串化为 JSON,这样您就不必考虑要保存/检索的内容,并且将避免"[object Object]"被保存。