从localStorage中的阵列中提取数据



我有一个函数,它从输入中获取数据,并在注册期间将其保存为数组中的数据。现在我想要另一个函数在登录期间检查数据是否存在以及是否匹配。如何仅使用javascript来完成此操作?简而言之,我需要一个功能来检查用户输入的数据是否存在,如果存在,请将其登录

function saveData() {
let name, email, password;
name = document.getElementById("username").value;
email = document.getElementById("email").value;
password = document.getElementById("password").value;
let user_records = new Array();
user_records = JSON.parse(localStorage.getItem("users"))
? JSON.parse(localStorage.getItem("users"))
: [];
if (
user_records.some((v) => {
return v.email == email;
})
) {
alert("Email wykorzystany");
} else {
user_records.push({
name: name,
email: email,
password: password,
});
localStorage.setItem("users", JSON.stringify(user_records));
}
}

我知道注册不应该这样做。我这么做只是为了学习新东西。

这是一个基本的登录,当你验证emmail和密码正确时,你可以做任何你想要的

function checkData() {
const name = document.getElementById('username').value;
const password = document.getElementById('password').value;
let user_records = JSON.parse(localStorage.getItem('users')) || [];
if (
user_records.find((user) => {
return user.name == name && user.password == password;
})
) {
alert('Logged in');
// do your things here
} else {
alert('wrong email or password');
// do your things here
}
}
<input id="username" />
<input id="password" />
<input type="submit" value="submit" onClick="checkData()" />

额外:这是一件只能用于学习目的的事情,它是向本地存储添加一个密钥,例如:localStorage.setItem('loggedIn',true(,并在每一页中设置一个该值的检查,如果为true则显示页面,如果为false则重定向到登录。在现实世界中,我们使用JWT令牌,其中包含有关用户的所有信息等。你可以在谷歌上搜索JWT令牌身份验证,并了解到,维奇在前端世界中非常有用

function saveAndTestUser() {
// here use const as they are not updated
const name = document.getElementById("username").value;
const email = document.getElementById("email").value;
const password = document.getElementById("password").value;
// Get all the records of the users
// prefer camelcase : not a rule though but it's better this way
const storedUsers = localStorage.getItem('users')
// if there are no stored users then assign empty array 
// so that we don't get unexpected errors
const userRecords = storedUsers ? JSON.parse(storedUsers): []
// Checking if email already exists
if(userRecords.some(user => user.email === email)){
alert("user already exists")
return false; // stops the function execution
}

// If email doesn't exists then the code below will be executed
// Similar to if-else
// Add current record to existing records
const newRecords = [...storedUsers, {name, email, password}] 
// Set the new record to storage
localStorage.setItem("users", JSON.stringify(newRecords));

}

最新更新