javascript 如何使用本地存储为单个键创建多个值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24544861/
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
How to create a multiple values for a single key using local storage
提问by user1853128
As we all know local storage is a key value pair. Trying to create a multiple values to a single key. But unable to get how to pass the multiple values for a single key.
众所周知,本地存储是一个键值对。尝试为单个键创建多个值。但无法获得如何为单个键传递多个值。
Here it is simple what have created.
在这里,创建的内容很简单。
var value = "aa"
localStorage.setItem("testKey", value);
var test = localStorage.getItem("testKey");
alert(test);
Now here what want to achieve is testKey
should have aa, bb and cc
values.
现在这里想要实现的是testKey
应该有aa, bb and cc
值。
If it is possible can anyone please help me out with a sample.
如果可能的话,任何人都可以帮我提供样品。
Note:
笔记:
Will localStorage values work for native app.
localStorage 值是否适用于本机应用程序。
回答by Azmisov
This is not possible with localstorage. However, you can store a JSON string as the value for the key, and with a little post-processing, you can extract your three variables:
这对于本地存储是不可能的。但是,您可以存储一个 JSON 字符串作为键的值,并通过一些后处理,您可以提取您的三个变量:
var value = ["aa","bb","cc"]
localStorage.setItem("testKey", JSON.stringify(value));
var test = JSON.parse(localStorage.getItem("testKey"));
alert(test);
回答by flamingcow
A single key can only have a single string value in localStorage. You can have multiple keys with different names, or you can do some encoding of the values. For example, you could put all your values in an Array, then encode it using JSON.stringify() and store the result in localStorage. When you read the data back, you can use JSON.parse() to turn it back into an Array.
单个键在 localStorage 中只能有一个字符串值。您可以有多个具有不同名称的键,或者您可以对值进行一些编码。例如,您可以将所有值放在一个数组中,然后使用 JSON.stringify() 对其进行编码并将结果存储在 localStorage 中。当您读回数据时,您可以使用 JSON.parse() 将其转回数组。
回答by Mun
<form>
<label>Mortgage Amount</label>
<input type="text" id="amount">
<label>Interest Rate % </label>
<input type="text" id="interest">
<label>Mortgage Period (Years)</label>
<input type="text" id="period">
<input type="button" value="Submit" id="btn">
<input type="button" value="GetLocalStorage" id="localbtn">
</form>
<script>
$(document).ready(function () {
$("#btn").click(function () {
var principal = $("#amount").val();
var interest = $("#interest").val();
var years = $("#period").val();
var item = [];
item.push(principal,interest,years);
localStorage.item += JSON.stringify({ "principalAmount": principal, "interestAmount": interest, "Period": years });
});