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

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

HTML5/JavaScript: Store Dynamic Variable Name and Value in localStorage

javascripthtmlvariablesdynamiclocal-storage

提问by Mark Rummel

I would like to store the value yesinto localStorage with a key of movie1using javascript. However, I want the 1part of the key to be dynamic based on whatever movieIDis 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 user1450955

I think

我认为

localStorage.setItem('movie' + movieID, 'yes');

is actually a helper in a library usage and is not official.

实际上是图书馆使用的帮手,而不是官方的。