I'm making a login/sign up form as a small personal project and I've ran into a slight snag.
All new users are stored in local storage.
When users login, I want to retrieve all the users from local storage and loop through them to see if the login details match the users sign up details.
I have basically created the code, I just can't get the if/else
statement to work correctly. It returns true
if the value is true
, but keeps on looping through and returns false
for the ones that aren't true
.
How do I get the loop to stop at the first true
value?
Here is my code:
// gather information and loop through users array
document.querySelector("#login").addEventListener("click", function(e)
{
// login details gathered from user
var logId = document.getElementById("logId").value;
var logPass = document.getElementById("logPass").value;
// get all the users from local stroage and loop through
var allUsers = JSON.parse(localStorage.getItem("users"));
allUsers.forEach(function(user) {
if (user.userId === logId && user.userPassword === logPass) {
console.log("true");
} else {
console.log("fasle");
}
});
// prevent form from submitting
e.preventDefault();
});
I'm making a login/sign up form as a small personal project and I've ran into a slight snag.
All new users are stored in local storage.
When users login, I want to retrieve all the users from local storage and loop through them to see if the login details match the users sign up details.
I have basically created the code, I just can't get the if/else
statement to work correctly. It returns true
if the value is true
, but keeps on looping through and returns false
for the ones that aren't true
.
How do I get the loop to stop at the first true
value?
Here is my code:
// gather information and loop through users array
document.querySelector("#login").addEventListener("click", function(e)
{
// login details gathered from user
var logId = document.getElementById("logId").value;
var logPass = document.getElementById("logPass").value;
// get all the users from local stroage and loop through
var allUsers = JSON.parse(localStorage.getItem("users"));
allUsers.forEach(function(user) {
if (user.userId === logId && user.userPassword === logPass) {
console.log("true");
} else {
console.log("fasle");
}
});
// prevent form from submitting
e.preventDefault();
});
Share
Improve this question
edited Jul 25, 2018 at 23:32
Davide Cannizzo
3,1341 gold badge30 silver badges32 bronze badges
asked Jan 20, 2018 at 10:27
jimbobjimbob
731 gold badge2 silver badges6 bronze badges
2
|
7 Answers
Reset to default 12I would recommend using .some
. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
This will return true
if any of the user's match to your requirement else false
let isUserMatched = allUsers.some(function(user) {
return user.userId === logId && user.userPassword === logPass)
});
if(isUserMatched){
// do something
}
there is no easy way to short circuit the forEach
, what you could do is use a traditional for loop like this
// gather information and loop through users array
document.querySelector("#login").addEventListener("click", function(e) {
// login details gathered from user
var logId = document.getElementById("logId").value;
var logPass = document.getElementById("logPass").value;
// get all the users from local stroage and loop through
var allUsers = JSON.parse(localStorage.getItem("users"));
for (var i = 0; i < allUsers.length; i++) {
if(user.userId === logId && user.userPassword === logPass){
console.log("true");
break;
} else {
console.log("false");
}
}
// prevent form from submitting
e.preventDefault();
});
According to the MDN documentation:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool. Use a plain loop or for...of instead. If you are testing the array elements for a predicate and need a Boolean return value, you can use every() or some() instead. If available, the new methods find() or findIndex() can be used for early termination upon true predicates as well.
Alternatively, what you could also possibly do is
var currentUser = allUsers.find(function fn(user) {
return user.userId === logId && user.userPassword === logPass;
}
Hope it helps
Use a normal for loop (not foreach) and use break; to come out of the for loop when the condition is true
forEach
isn't really a statement. It's just a function
that calls the passed function
in its parameter. So, it's totally impossible to handle something in its for
statement.
At this point I suggest you to use for
statement and select the index from the array:
for (let length = allUsers.length, i = 0, user = allUsers[i]; i < length; i++, user = allUsers[i]) {
//Here's user that is the same such than the parameter in your function.
}
Now you can add a condition link an "until". Let consider the variable condition
:
var condition = false;
for (let length = allUsers.length, i = 0, user = allUsers[i]; i < length && !condition; i++, user = allUsers[i]) {
//When condition is true, the condition of the for statement gets false and the for cycle stops.
}
Or:
var condition = false;
for (let length = allUsers.length, i = 0, user = allUsers[i]; i < length; i++, user = allUsers[i]) {
if (condition)
break;
//When condition is true, the above if statement is passed and for cycle is breaked.
}
You can also create your own forEach
function:
//In this example I overwrite the normal forEach function
Array.prototype.forEach = function(callback) {
window.$break = function() {
window._break = true;
};
window.$continue = function() {
window._continue = true;
};
for (let l = this.length, i = 0, e = this[i]; i < l; i++, e = this[i]) {
if (window._break) {
window._break = false;
break;
}
if (window._continue) {
window._continue = false;
continue;
}
callback(e, i);
}
};
Now you have to combine the function $break()
with the return
statement in the function
:
var condition = false;
allUsers.forEach(function(user) {
if (condition) {
$break();
return;
}
});
The latter solution I posted, I also written in this fiddle.
Just use normal for (or some), foreach just calls passed function on each element there is no way to break.
u can use try - catch to stop forEach , i write a sample code u can change as u want
var q = [1,2,3,4,5,6,7,8,9,10]
try
{
q.forEach(function (x){
print(x)
if (x==3)
throw "bye bye"
})
}
catch(e)
{
print(e)
}
return
? – Ayush Gupta Commented Jan 20, 2018 at 10:30forEach
work likecontinue
infor
, check my answer soulotion is try-catch – Nozar Safari Commented Jan 20, 2018 at 11:08