【问题标题】:Check if user is already existed in localStorage检查用户是否已存在于 localStorage
【发布时间】:2021-02-11 21:12:12
【问题描述】:

const firstName = document.getElementById("firstName");
const lastnName = document.getElementById("lastName");
const email = document.getElementById("newEmail");
const password = document.getElementById("newPassword");

const btnSignup = document.getElementById("btn-signup");

btnSignup.onclick = function () { // when mouse click "signup" button
    const first_name = firstName.value; // getting the value of firstName and so on..
    const last_name = lastName.value;
    const e_mail = newEmail.value;
    const pass_word = newPassword.value;

    if (first_name && last_name && e_mail && pass_word) {
 
        //set user input into JSON
        let user_data = {
            firstName: first_name,
            lastName: last_name,
            email: e_mail,
            password: pass_word
        }
        
        //get to localstorage if there is existing user ||or make empty array[]
        let clientsArr = JSON.parse(localStorage.getItem('users')) || [];
        
        //ipush ang new user sa array
        clientsArr.push(user_data);

        //save to localstorage
        localStorage.setItem('users', JSON.stringify(clientsArr));
    }
        // location.reload();
        else if (user_data === localStorage.getItem('users')) { // THIS IS THE CODE THAT I AM TRYING
            alert("User already existed");
        } 
};

我正在尝试在屏幕上显示错误消息或在浏览器上显示警告,此代码确实有效,问题是如何识别本地存储中是否存在现有用户。我想说的是,如果内存中有现有用户,您的“登录”将不接受。谢谢!我对要运行的代码添加了注释。

【问题讨论】:

  • 试试这样的if (localStorage.getItem("user") === null) { // your code goes here }

标签: javascript html arrays dom local-storage


【解决方案1】:

几点:

  • JavaScript 通过内存引用(RAM 上的位置)比较对象。
  • let 变量绑定到词法范围 {}。因此,user_data 在第二个 else if 语句中将不可用。
  • 奖励:使用提前退出来保持代码干净。
  • 使用唯一标识符,例如id。在示例中,我将对象转换为字符串并进行比较。

// Fields
const firstName = document.getElementById("firstName");
const lastnName = document.getElementById("lastName");
const email = document.getElementById("newEmail");
const password = document.getElementById("newPassword");
// Button
const btnSignup = document.getElementById("btn-signup");

function signUp() {

  const first_name = firstName.value;
  const last_name = lastName.value;
  const e_mail = newEmail.value;
  const pass_word = newPassword.value;

  // If either of the values is empty
  if (!first_name || !last_name || !e_mail || !pass_word) {
    return;
  }

  //set user input into JSON
  let user_data = {
    firstName: first_name,
    lastName: last_name,
    email: e_mail,
    password: pass_word
  }
  
  // convert to string
  let user_data_str = JSON.stringify(user_data)

  //get to localstorage if there is existing user ||or make empty array[]
  let clientsArr = JSON.parse(localStorage.getItem('users')) || [];
  
  // Convert to string
  
  // Search the list if 
  const userExists = clientsArr.find(user => JSON.stringify(user) === user_data_str);
  
  if (userExists) {
    return alert('User already exists')
  }
    
  //ipush ang new user sa array
  clientsArr.push(user_data);

  //save to localstorage
  localStorage.setItem('users', JSON.stringify(clientsArr));

}
// Attach listener
btnSignup.addEventListener('click', signUp);
<input id="firstName" />
<input id="lastName" />
<input id="newEmail" />
<input id="newPassword" />
<button id="btn-signup">Sign up</button>

【讨论】:

  • 它正在工作!谢谢亚当!我可以再问一次,如果用户尝试将电子邮件和密码登录到登录页面怎么办?问太多了吗?谢谢。
  • 亚当,我的意思是,如果本地存储中的数据将在“登录表单”中使用怎么办?
  • 我建议为此使用后端数据库。我的假设是您这样做是为了练习;可以将LocalStorage 视为数据库。 :)
【解决方案2】:

如果您在添加到 localStorage 中的“用户”之前尝试检查用户是否已经存在,您可以执行以下操作:

const firstName = document.getElementById("firstName");
const lastnName = document.getElementById("lastName");
const email = document.getElementById("newEmail");
const password = document.getElementById("newPassword");

const btnSignup = document.getElementById("btn-signup");

btnSignup.onclick = function () {
    const first_name = firstName.value;  
    const last_name = lastName.value;
    const e_mail = newEmail.value;
    const pass_word = newPassword.value;

    // Only get localstorage item once
    let clientsArr = JSON.parse(localStorage.getItem('users')) || [];

    // Only execute those lines if we have the data that we need
    if (first_name && last_name && e_mail && pass_word) {
 
        let user_data = {
            firstName: first_name,
            lastName: last_name,
            email: e_mail,
            password: pass_word
        }
        // Check if the user already exists to show an alert or add it to the list
        if(clientsArr.includes(user_data)) {
            alert("User already existed");
        } else {
             clientsArr.push(user_data);
             localStorage.setItem('users', JSON.stringify(clientsArr));
        }

    }

};

【讨论】:

  • 谢谢Casana,我会试试这个,像我这样的初学者请耐心等待,上帝保佑!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-05
  • 2021-12-19
  • 2021-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多