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
4 Answers 4
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
Comments
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.
Comments
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"));
Comments
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")
2 Comments
code var name = ["heine", "hans"]; var password = ["12343", "1234"]; var i, temp; function login(login, pass) { console.log("start") for(temp = 0; temp < name.length; temp++) { console.log(temp) if((i = name.indexOf(login)) !== -1){ console.log("name") if(password[temp] === pass) console.log("Logged!"); } } } login("hans", "1234")
indexOf()password[i] === 1234will however always be false, due to the passwords being strings and the usage of===nameis a string. Which is very odd.