Reputation: 11
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
If the word hans
is in the array, than i need the position from the word in the array
Upvotes: 1
Views: 105
Reputation: 686
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")
Upvotes: 0
Reputation: 17190
In your case, you can also try something like this with 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"));
Upvotes: 0
Reputation: 207501
Problem here is name is window.name which is a string..
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.
Upvotes: 0
Reputation: 92440
You might find some()
handy for this. It will pass the index into the callback which you can use to find the corresponding value from the passwords
array:
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
Upvotes: 2