You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

新手任务求助:实现基于Local Storage的多账号密码存储工具(需JS代码)

密码保存工具实现(JavaScript)

针对你需要的密码保存工具,我写了一套简洁的实现代码,包含存储到数组和LocalStorage、按唯一ID查询的核心功能,适合前端新手理解:

// 初始化存储数组,优先从LocalStorage读取,没有则为空数组
let passwordStore = JSON.parse(localStorage.getItem('passwordStore')) || [];

// 添加密码项函数:验证ID唯一,然后存入数组和LocalStorage
function addPasswordItem(id, email, password) {
  // 检查ID是否已存在
  const exists = passwordStore.some(item => item.id === id);
  if (exists) {
    alert('该唯一ID已存在,请更换');
    return false;
  }
  // 创建新项
  const newItem = { id, email, password };
  // 添加到数组
  passwordStore.push(newItem);
  // 同步到LocalStorage
  localStorage.setItem('passwordStore', JSON.stringify(passwordStore));
  alert('保存成功');
  return true;
}

// 按ID查询密码项函数
function getPasswordItem(id) {
  // 查找匹配项
  const item = passwordStore.find(item => item.id === id);
  if (item) {
    return { email: item.email, password: item.password };
  } else {
    alert('未找到对应ID的记录');
    return null;
  }
}

// 示例用法
// 添加一条记录:ID为"github",邮箱和密码自定义
// addPasswordItem('github', 'mygithub@example.com', 'mygithubpass123');
// 查询记录
// const result = getPasswordItem('github');
// if (result) console.log('查询结果:', result);

代码逐段解释

1. 初始化存储数组

  • let passwordStore = JSON.parse(localStorage.getItem('passwordStore')) || [];
    • 页面加载时,先尝试从LocalStorage读取已保存的密码数据(LocalStorage只能存字符串,所以用JSON.parse转成数组)
    • 如果LocalStorage里没有数据,就初始化一个空数组

2. 添加密码项函数(addPasswordItem)

  • 先通过some方法检查传入的唯一ID是否已经存在,避免重复存储
  • 如果ID唯一,就创建包含id、email、password的对象,添加到数组
  • 用JSON.stringify把数组转成字符串,同步存入LocalStorage,确保刷新页面后数据不丢失
  • 用alert给用户反馈操作结果,新手友好

3. 按ID查询函数(getPasswordItem)

  • 用find方法在数组里匹配对应ID的项
  • 找到就返回包含邮箱和密码的对象,没找到就提示用户并返回null

4. 示例用法

  • 注释里写了添加和查询的调用方式,取消注释就能直接测试

内容的提问来源于stack exchange,提问作者ayyan Mohsin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 06:12:43