LoginSignup
x9jdzhcc72mxib2azgcyo
@x9jdzhcc72mxib2azgcyo

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

for文で二次元配列の値の正誤について

解決したいこと

仮パスワード(idとpw)を二次元配列で作りfor文でもし、idとpwが一致すれば画面遷移、そうでなければアラート表示といった感じにしたいのですが、for文がうまく反映されず困っています。

発生している問題・エラー

出ているエラーメッセージを入力

例)

function logincheck(){
const id = document.getElementById('id').value;
const pw = document.getElementById('pas').value;

//ユーザー仮ナンバー
const usernum=[
['ss', '2222'],
['df', '4444'],
['we', '5555'],
];

//ID PW未入力時
if(id === "" && pw === ""){
  alert("IDとパスワードは必須入力です");

//ID未入力時
}else if(id === ""){
  alert("IDは必須入力です");

//PW未入力時
}else if(pw === ""){
  alert("パスワードは必須入力です");
}else{
//ID PW一致チェック
  for(let i=0; i<usernum.length; i++){
        let item = usernum[i];
        if(item[0] === id && item[1] === password){
        window.location.href='html トップ画面.html';
    }else{
      alert("IDとパスワードが一致しません");

    }
  });
}
}

自分で試したこと

findindexを試したがどう書けばよいか分からなかった。

0

2Answer

for文はほぼもう使わないので、よっぽどの事がない限りそこまで意識して使う必要はないかも。

後、if文の嵐は疲れるので、複数の条件があれば先にチェックして順々に抜け出ていくとif文のネストが起きなくて読むのが楽になります。

function logincheck() {
  const id = document.getElementById("id").value;
  const pw = document.getElementById("pas").value;

  if (id === "" && pw === "") {
    alert("IDとパスワードは必須入力です");
    return;
  }

  if (id === "") {
    alert("IDは必須入力です");
    return;
  }

  if (pw === "") {
    alert("パスワードは必須入力です");
    return;
  }

  //ユーザー仮ナンバー
  const usernum = [
    ["ss", "2222"],
    ["df", "4444"],
    ["we", "5555"],
  ];

  const found = usernum.find(
    ([idFromTable, passwordFromTable]) =>
      idFromTable === id && passwordFromTable === pw
  );

  if(!found){
    alert("IDとパスワードが一致しません");
    return;
  }

  window.location.href = "html トップ画面.html";
}

1

まず「ID PW一致チェック」をする際にpwpasswordに変わってしまっていますね。

また、一致チェックをするたびに「ページ遷移またはアラート表示」が走ってしまうので、フラグ管理してループが終わった後に「ページ遷移またはアラート表示」すればいいと思います。

書き方としては以下のような形になると思います。

//ID PW一致チェック
var isMatch = false;
for(let i=0; i<usernum.length; i++){
    let item = usernum[i];
    if(item[0] === id && item[1] === pw){
        isMatch =true;
        break;
    }
}

if(isMatch){
    window.location.href='html トップ画面.html';
}
else{
    alert("IDとパスワードが一致しません");
}
0

Comments

  1. 動きました。苦戦していたので、本当に助かりました。ありがとうございました!

Your answer might help someone💌