【问题标题】:JSON and JS repeat check index number (PURE JAVASCRIPT)JSON和JS重复检查索引号(PURE JAVASCRIPT)
【发布时间】:2022-01-09 07:24:15
【问题描述】:

我正在通过 JSON 创建一个登录站点,我想检查用户名是否与密码匹配(通过使用数组索引来匹配用户名、密码和电子邮件)但我不知道如何查看用户名与任何索引号匹配,并且如果数组中有与密码部分中的索引对应的索引。我可以将 indexOf 与递归(调用自身的函数)一起使用,但我必须将检查的索引增加 1,我不知道该怎么做。 (搜索了任何东西,但我找不到任何东西) 像这样:

{
"usernames": [
"Supa", "Marwan", "Jason", "Jacob",
]
"passwords": [
"placeholder", "placeholder1", "placeholder2", "placeholder3",
]
}
function checkDetails(username, password) {
let message = document.getElementById("placeholder");
let password = document.getElementById("placeholder1");
let username = document.getElementById("placeholder2");

//part I am struggling with
let usernames = json.parse("usernames");
let passwords = json.parse("passwords");
message.innerHTML = (username === usernames[/*i want this to increment to check*/]) ? 
message.innerHTML = (password === indexOf(/*I want this to be the index of the one 
index that IS true to the conditional above*/)) ? m
essage.innerHTML = "Success with logging in" :
 message.innerHTML = "Invalid username or password";

【问题讨论】:

  • 您在 checkDetails 示例中缺少右括号,并且在变量名 (message) 中间有一个换行符...
  • 我认为这是一个玩具项目,因为这种身份验证方法完全不安全。这里不需要递归。 json.parse 不是函数,应该是 JSON.parse。您在寻找indexOf,例如usernames.indexOf(username) >= 0?
  • 忽略您的代码的其他问题,看起来您想在这里使用长且不可读的三元表达式,无论出于何种原因,您都在寻找合适的测试。这只是data.usernames.indexOf(username) == data.passwords.indexOf(password)(尽管您还必须检查它们中的任何一个是否> -1)
  • 由于用户名和密码存储在数组中,并且每个人的密码和用户名都在同一个索引中,我希望它检查数组中每个用户名的文本,然后找到索引正确的数字并检查密码是否相同(使用您的示例,我无法检查 indexof 的文本以查看它是否正确并将其放入输入中。

标签: javascript json database


【解决方案1】:

正如 cmets 所证明的,您的 JSON 格式不正确,这是一种完全不安全的登录管理方式。也就是说,您可以通过以下方式测试用户名,如果存在,请检查是否有适当的密码签出。在函数的第一行,我们将用户名规范化为小写,并删除任何多余的空格。

let json = {
  "usernames": [
    "Supa", "Marwan", "Jason", "Jacob",
  ],
  "passwords": [
    "placeholder", "placeholder1", "placeholder2", "placeholder3",
  ]
}

function checkDetails(username, password) {
  let userindex = json.usernames.findIndex(u => u.toLowerCase().trim() === username.toLowerCase().trim());
  if (userindex === -1) {
    return 'username does not exist';
  } else if (json.passwords[userindex] !== password) {
    return 'wrong password';
  }
  return 'success!'
}

console.log(checkDetails('Supa1', 'placeholder1'))
console.log(checkDetails('Supa', 'placeholder1'))
console.log(checkDetails('Supa', 'placeholder'))

【讨论】:

    猜你喜欢
    • 2014-02-22
    • 2014-05-11
    • 1970-01-01
    • 2021-10-26
    • 2012-12-27
    • 2016-08-25
    • 2019-02-16
    • 2010-10-08
    • 1970-01-01
    相关资源
    最近更新 更多