gpt4 book ai didi

javascript - 使用本地存储的多个 key

转载 作者:行者123 更新时间:2023-12-03 12:19:05 25 4
gpt4 key购买 nike

我正在尝试使用以下代码为记录(用户名,密码,电子邮件)生成多个键(user_0,user_1,user_3 ...)我收到警报“数据已保存”,但没有保存任何内容在本地存储中。有人可以帮助我哪里出了问题吗?

$("#submit").click(function(){
if ('localStorage' in window && window['localStorage'] !== null) {
try {
e=$("#email").val();
u=$("#username").val();
p=$("#password").val();

function users(email,username,password){

this.email=email;
this.username=username;
this.password= password;

}
function createNewUser(eml,user,pass) {
var createdUser = new users(e,u,p);
//console.log(createdUser);
if ( localStorage.userCount == undefined ) {
localStorage.setItem('userCount', 0)
}
var userSize = parseInt(localStorage.userCount) + 1;
commitToStorage(userSize,createdUser);
}

function commitToStorage(objectCount,newObject) {
// The unique key of the object:
var item = 'user' + objectCount;
localStorage.setItem('userCount', objectCount);

// Put the object into storage
localStorage.setItem(item, JSON.stringify(users));
}
alert("The data was saved.");
return true;
}catch (e) {
if (e == QUOTA_EXCEEDED_ERR) {
alert('Quota exceeded!');
}
}
} else {
alert('Cannot store user preferences as your browser do not support local storage');
}
});

最佳答案

最好的选择是将所有用户对象存储在一个数组中,如果愿意,您可以使用数组索引向它们添加标识符

$("#submit").click(function(){
if ('localStorage' in window && window['localStorage'] !== null) {

var users;
if(!localStorage.users) { users = []; }
else {
users = JSON.parse(localStorage.users);
}

// don't stringify the data yet
var currentUser = {
"userNumber" : users.length,
"email" : $("#email").val(),
"username" : $("#username").val(),
"password" : $("#password").val(),
};

users.push(currentUser);

try {
localStorage.users = JSON.stringify(users);
console.log("The data was saved.");
return true;
}
catch (e) {
if (e == QUOTA_EXCEEDED_ERR) {
alert('Quota exceeded!');
}
}

else {
alert('Cannot store user preferences as your browser do not support local storage');
}
});

关于javascript - 使用本地存储的多个 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24523857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com