I am trying to determine whether or not an array holds a certain item. If it does, I would like to hold the function, otherwise it should get added.
function addPacking(item){
data.packings.forEach(function(entry){
if(item.name == entry.name){
return;
}
});
data.packings.push(item);
}
Unfortunately, the data is pushed even when the if condition is met. How do I prevent this behaviour without using an else
condition?
(I do not want to use else
because my actual code is a lot more complex than this and I'd like to keep it readable)
Edit:
Does forEach
execute asynchronously?
Using return within the callback of a forEach () loop does not stop the loop, instead it continues to the next element in the iteration. This happens because forEach () executes the callback function for each element of the array. To demonstrate this, let's look at the following example:
In fact, forEach () takes in a callback function that does return a value, but only within the scope created by forEach ().
JavaScript's forEach () function executes a function on every element in an array. However, since forEach () is a function rather than a loop, using the break statement is a syntax error: We recommend using for/of loops to iterate through an array unless you have a good reason not to.
How to Break Out of a JavaScript forEach () Loop 1. Use every () instead of forEach (). The every () function behaves exactly like forEach (), except it stops iterating... 2. Filter Out The Values You Want to Skip. Instead of thinking about how to break out of a forEach (), try thinking... 3. Use a ...
Old ways are sometimes the best. It's because you're passing a delegate function when calling .forEach
. The return
within the delegate is getting lost, and isn't applying to anything. To get your desired result, you'll want to exit the calling function addPacking
. This can be done using a simply for
loop.
function addPacking(item){
for (var i = 0; i < data.packings.length++; i++) {
if (item.name == data.packings[i].name) {
return;
}
}
data.packings.push(item);
});
This approach also supports older browsers, unlike some
, every
and forEach
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With