I’m looping through an object using for loop, and I would like to ignore some specific values when looping.
This block of code is responsible to loop through my object:
let acceptAll = function (rawContent){
for(let i in rawContent)
if(!rawContent[i]) return false;
return true
};
I have a value in rawContent that I would like to ignore when looping through, is that possible?
Many thanks in advance!
Advertisement
Answer
You have a couple of options:
ifcontinueifon its own
Here’s if continue:
for (let i in rawContent) {
if (/*...you want to ignore it...*/) {
continue; // Skips the rest of the loop body
}
// ...do something with it
}
Or if on its own:
for (let i in rawContent) {
if (/*...you DON'T want to ignore it...*/) {
// ...do something with it
}
}
Side note: That’s a for-in loop, not a for loop (even though it starts with for). JavaScript has three separate looping constructs that start with for:
Traditional
forloop:for (let i = 0; i < 10; ++i) { // ... }for-inloop:for (let propertyName in someObject) { // ... }(If you never change the value in
propertyNamein the loop body, you can useconstinstead oflet.)for-ofloop:for (let element of someIterableLikeAnArray) { // ... }(If you never change the value in
elementin the loop body, you can useconstinstead oflet.)