[英]How to find a word(string) in Javascript array?
我需要檢查數組中是否包含單詞
這是我的代碼,請幫忙
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
單詞在數組中,那么我需要從單詞在數組中的位置
您可能會找到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
您可以使用它。 我不確定這是否是您想要的。
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")
在您的情況下,您也可以嘗試使用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"));
這里的問題是名稱是window.name,它是一個字符串。
var name = ['heine', 'hans']; console.log(window.name, typeof window.name) var xname = ['heine', 'hans']; console.log(window.xname, typeof window.xname)
如果您位於全局范圍內,請將變量更改為另一個不保留的單詞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.