C++ for each, pulling from vector elements

For next examples assumed that you use C++11. Example with ranged-based for loops: You should use const auto &attack depending on the behavior of makeDamage(). You can use std::for_each from standard library + lambdas: If you are uncomfortable using std::for_each, you can loop over m_attack using iterators: Use m_attack.cbegin() and m_attack.cend() to get const iterators.

Loop through an array in JavaScript

Three main options: for (var i = 0; i < xs.length; i++) { console.log(xs[i]); } xs.forEach((x, i) => console.log(x)); for (const x of xs) { console.log(x); } Detailed examples are below. 1. Sequential for loop:  Run code snippet Pros Works on every environment You can use break and continue flow control statements Cons Too verbose Imperative Easy to have off-by-one errors (sometimes also … Read more

Loop through an array in JavaScript

Yes, assuming your implementation includes the for…of feature introduced in ECMAScript 2015 (the “Harmony” release)… which is a pretty safe assumption these days. It works like this: Or better yet, since ECMAScript 2015 also provides block-scoped variables: (The variable s is different on each iteration, but can still be declared const inside the loop body as long as it isn’t modified there.) A … Read more

Java 8 Iterable.forEach() vs foreach loop

The better practice is to use for-each. Besides violating the Keep It Simple, Stupid principle, the new-fangled forEach() has at least the following deficiencies: Can’t use non-final variables. So, code like the following can’t be turned into a forEach lambda: Can’t handle checked exceptions. Lambdas aren’t actually forbidden from throwing checked exceptions, but common functional … Read more