简体   繁体   English

如何在Javascript数组中查找单词(字符串)?

[英]How to find a word(string) in Javascript array?

I need to check if my array has the word 我需要检查数组中是否包含单词

This is my code please help 这是我的代码,请帮忙

  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, but why, it must be a 1 consoleout = 6,但为什么必须为1

If the word hans is in the array, than i need the position from the word in the array 如果hans单词在数组中,那么我需要从单词在数组中的位置

You might find some() handy for this. 您可能会找到some()方便的方法。 It will pass the index into the callback which you can use to find the corresponding value from the passwords array: 它将把索引传递到回调中,您可以使用该回调从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 

You may use this. 您可以使用它。 I am not sure if it is what you want. 我不确定这是否是您想要的。

let names = ["heine", "hans"];
let password = ["12343", "1234"];
let i, temp;

function log(login, pass) {
    if((i = names.indexOf(login)) !== -1){
        if(password[i] === pass)
            console.log("Logged!");
    }
}

log("hans", "1234")

In your case, you can also try something like this with findIndex : 在您的情况下,您也可以尝试使用findIndex这样的操作

 const usernames = ['heine', 'hans']; const passwords = ['12343', '1234']; function login(user, pass) { let userIdx = usernames.findIndex(x => x === user); // On a real application do not give any tip about which is // wrong, just return "invalid username or password" on both cases. if (userIdx < 0) return "Invalid username!"; if (pass !== passwords[userIdx]) return "Invalid password!"; return "Login OK!" } console.log(login("heine", "12343")); console.log(login("hans", "lala")); 

Problem here is name is window.name which is a string.. 这里的问题是名称是window.name,它是一个字符串。

 var name = ['heine', 'hans']; console.log(window.name, typeof window.name) var xname = ['heine', 'hans']; console.log(window.xname, typeof window.xname) 

Change your variable to another word that is not reserved if you are in global scope. 如果您位于全局范围内,请将变量更改为另一个不保留的单词。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM