gpt4 book ai didi

javascript - 如何将新数组添加到本地存储中的当前数组元素?

转载 作者:行者123 更新时间:2023-11-28 01:22:53 26 4
gpt4 key购买 nike

我在本地存储中创建了一个用户数组:

let btnSignUp = document.getElementById("btnSignUp");
btnSignUp.addEventListener('click', (e) => {
let existingUsers = JSON.parse(localStorage.getItem("allUsers"));
if (existingUsers == null) existingUsers = [];

let userLogin = document.getElementById('authLogin').value;
let userEmail = document.getElementById('authEmail').value;
let userPassword = document.getElementById('authPassword').value;
let userConfirmPassword = document.getElementById('authConfirmPassword').value;
if (userPassword == userConfirmPassword) {
let users = {
"login": userLogin,
"email": userEmail,
"password": userPassword,
"contacts": []
};
localStorage.setItem("users", JSON.stringify(users));
// Save allEntries back to local storage
existingUsers.push(users);
localStorage.setItem("allUsers", JSON.stringify(existingUsers));
} else {
alert("Password and confirm password must be the same");
}
}, false);

现在我需要为选定的用户创建一个联系人数组。联系人应如下所示:

let userSurname = document.getElementById('_surname').value;
let userName = document.getElementById('_name').value;
let userCountry = document.getElementById('_country').value;
let userCity = document.getElementById('_city').value;
let userEmail = document.getElementById('_email').value;
let userPhone = document.getElementById('_phone').value;
let userWorkPlace = document.getElementById('_workPlace').value;

let contact = {
"surname": userSurname,
"name": userName,
"country": userCountry,
"city": userCity,
"email": userEmail,
"phone": userPhone,
"workPlace": userWorkPlace
};
localStorage.setItem("contact", JSON.stringify(contact));

请告诉我怎么做。

最佳答案

创建联系人对象数组。JSON.stringify联系人对象数组

 let contacts = [];
let contactObj = {
"surname": userSurname,
"name": userName,
"country": userCountry,
"city": userCity,
"email": userEmail,
"phone": userPhone,
"workPlace": userWorkPlace
};
contacts.push(contactObj)
localStorage.setItem("contact", JSON.stringify(contacts));

关于javascript - 如何将新数组添加到本地存储中的当前数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51399014/

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