首页 > 解决方案 > 如何在 Javascript 数组中查找单词(字符串)?

问题描述

我需要检查我的数组是否有这个词

这是我的代码请帮忙

    var name = ['heine', 'hans'];
    var password = ['12343', '1234'];
    function login() {
    var pos;
        if(name.includes('hans')) {
            console.log("enthält");
            pos = name.indexOf('hans');
            console.log(pos)
            if(password[pos] === '1234') {
                console.log("angemeldet")
            }
        }
      }

consoleout = 6,但是为什么,它必须是 1

如果单词hans在数组中,那么我需要数组中单词的位置

标签: javascriptarrays

解决方案


你可能会发现some()这很方便。它将索引传递给回调,您可以使用它从passwords数组中找到相应的值:

function test(name, pw) {
  let names = ["heine", "hans"];
  let passwords = ["12343", "1234"];
  // is there `some` name/pw combinations that matches?
  return names.some((n, index) => name == n && pw == passwords[index])
}

console.log(test("hans", '1234'))   // true
console.log(test("hans", '12345'))  // false
console.log(test("hans", '12343'))  // false

console.log(test("heine", '12343')) // true
console.log(test("mark", '12343'))  // false
 


推荐阅读