You are working in a chocolate store, and your boss tells you to check wether all chocolates (there are chili chocolate, caramel chocolate and coffee chocolate) are delicious. He tells you the following:
Go through all chocolates, and for each chocolate, taste it, if it is fine, tell me that everything is fine, otherwise tell me that something is wrong1
You start with the first chocolate, which is chili chocolate, it tastes delucious, you go to your boss and tell him that everything is fine. Your boss yells at you because you haven't tasted the caramel chocolate and the coffee chocolate yet.
You realize that your boss actually wanted you to do:
Go through the chocolates, for each chocolate, taste it, if it doesnt taste well tell, tell me immeadiately, otherwise continue until you tasted them all, then return to me and tell me that everything is fine.2
Or in code:
// 1
function checkChocolates(chocolates) {
for(const chocolate of chocolates) {
if(isTasty(chocolate)) {
return true;
} else {
return false;
}
}
}
// 2
function checkChocolates(chocolates) {
for(const chocolate of chocolates) {
if(isTasty(chocolate)) {
continue; // this could be omitted, as a loop keeps looping nevertheless
} else {
return false;
}
}
return true;
}
As this is a very common task in programming, there is already a shorter way to express this:
if(chocolates.every(isTasty)) {
alert("all chocolates are fine");
} else {
alert("Oh, that doesnt taste good");
}
whereas isTasty
is a function taking a chocolate and returning either true or false.
If you didn't grasp it yet, just try it out! Buy some chocolate, and taste it! If someone tells you "eating choclate isn't learning", respond with "I'm doing rubber duck debugging" and no one can complain :)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…