繁体   English   中英

使用Cookie记住数组中的所有值-javascript

[英]remember all values in an array using cookies - javascript

我希望能够使用cookie记住数组中的所有值,但不知道如何。 我也在使用js-cookies。

 Here is my code:
 var usernames = new Array();
 var input = $('#input').val();
 usernames.push(input);
 // each time something is inputted, it'll be saved to the
 // array usernames. I want it so that when refreshed, all
 // of the inputs remain in 'usernames'
 alert(usernames);

如前所述, localStorage是存储此数据的更好位置,但是使用Cookies遵循相同的步骤,只需要获取Cookiesset / get方法即可 首先,您需要查看是否有值。 如果有,则需要解析它。 更新数组后,需要将值转换为字符串并存储。

//Read local storage to see if we have anything saved
var lsUserNames = localStorage.getItem("usernames");
//Get the usernames array
var usernames = lsUserNames ? JSON.parse(lsUserNames) : [];

//Just using prompt to get the username instead of making form
var uname = window.prompt("Enter Name");
if(uname) usernames.push(uname);

//set the updated array to local storage
localStorage.setItem("usernames", JSON.stringify(usernames));
console.log(usernames.join());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM