Page 95 - JavaScript
P. 95
Equivalent in any JavaScript version:
var arr = [2, 4, 7, 9];
for (var i = 0; i < arr.length && arr[i] !== 7; i++) {
console.log(arr[i]);
}
Libraries
Finally, many utility libraries also have their own foreach variation. Three of the most popular ones
are these:
jQuery.each(), in jQuery:
$.each(myArray, function(key, value) {
console.log(value);
});
_.each(), in Underscore.js:
_.each(myArray, function(value, key, myArray) {
console.log(value);
});
_.forEach(), in Lodash.js:
_.forEach(myArray, function(value, key) {
console.log(value);
});
See also the following question on SO, where much of this information was originally posted:
• Loop through an array in JavaScript
Filtering Object Arrays
The filter() method accepts a test function, and returns a new array containing only the elements
of the original array that pass the test provided.
// Suppose we want to get all odd number in an array:
var numbers = [5, 32, 43, 4];
5.1
var odd = numbers.filter(function(n) {
return n % 2 !== 0;
});
6
https://riptutorial.com/ 52

