HTML5/JavaScript:在 localStorage 中存储动态变量名称和值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9896348/
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
HTML5/JavaScript: Store Dynamic Variable Name and Value in localStorage
提问by Mark Rummel
I would like to store the value yes
into localStorage with a key of movie1
using javascript. However, I want the 1
part of the key to be dynamic based on whatever movieID
is set to.
我想使用 javascriptyes
的键将值存储到 localStorage 中movie1
。但是,我希望1
密钥的一部分根据movieID
设置的内容是动态的。
This is what I currently have, but it isn't working:
这是我目前拥有的,但它不起作用:
movieID = 1;
localStorage.movie + movieID = 'yes';
Any thoughts or insight on how I can accomplish this would be greatly appreciated. Thanks!
任何关于我如何实现这一目标的想法或见解将不胜感激。谢谢!
回答by stewe
Try this:
试试这个:
localStorage['movie'+movieID] = 'yes';
回答by Annie
You can use the setItem function to store values in local storage:
您可以使用 setItem 函数将值存储在本地存储中:
localStorage.setItem('movie' + movieID, 'yes');
Then later when you want to check the value, you can use
然后当你想检查值时,你可以使用
localStorage.getItem('movie' + movieID);
回答by Rick
Check out square brackets for properties.
查看方括号中的属性。
回答by user1450955
I think
我认为
localStorage.setItem('movie' + movieID, 'yes');
is actually a helper in a library usage and is not official.
实际上是图书馆使用的帮手,而不是官方的。