This post explains three approaches for extracting information from arrays and objects:
function findEvenNumber(arr) { loop: { // label for(var i=0; i<arr.length; i++) { if ((arr[i] % 2) === 0) { console.log("Found: "+arr[i]); break loop; } } console.log("No even number found."); } console.log("DONE"); }
for ([start]; [condition]; [final-expression]) statementRules:
var arr = [ "a", "b", "c" ]; for(var i=0; i < arr.length; i++) { console.log(arr[i]); }
for (variable in object) statementRules:
> var arr = [ "a", "b", "c" ]; > arr.foo = true; > for(var key in arr) { console.log(key); } 0 1 2 fooPitfall: Iterates over inherited properties.
function Person(name) { this.name = name; } Person.prototype = { describe: function() { return "Name: "+this.name; } }; var person = new Person("Jane"); for(var key in person) { console.log(key); }Output:
name describeSkip inherited properties: via hasOwnProperty().
for(var key in person) { if (person.hasOwnProperty(key)) { console.log(key); } }
function(callback, [thisValue])Parameters:
function([element], [index], [collection])
var arr = [ "apple", "pear", "orange" ]; arr.forEach(function(elem) { console.log(elem); });Pitfall: forEach() does not support break. Use every() instead:
function breakAtEmptyString(arr) { arr.every(function(elem) { if (elem.length === 0) { return false; // break } console.log(elem); return true; // don’t forget! }); }every() returns false if a break happened and true, otherwise. This allows you to react to the iteration finishing successfully (something that is slightly tricky with for loops). Caveat: You need to return a “true” value to keep going. If you want to avoid that, you can use some() and return true to break:
function breakAtEmptyString(arr) { arr.some(function(elem) { if (elem.length === 0) { return true; // break } console.log(elem); // implicit: return undefined (interpreted as false) }); }
function([element], [index], [collection])Methods:
function(previousElement, currentElement, currentIndex, collection)Methods:
// Sum of all array elements: [17, 5, 4, 28].reduce(function(prev, cur) { return prev + cur; });
> Object.keys({ first: "John", last: "Doe" }) [ 'first', 'last' ]
> Object.getOwnPropertyNames(Number.prototype) [ 'toExponential' , 'toString' , 'toLocaleString' , 'toPrecision' , 'valueOf' , 'toJSON' , 'constructor' , 'toFixed' ] > Object.keys(Number.prototype) []Comment: The main reason that prototype methods are not enumerable is to hide them from iteration mechanisms that include inherited properties.
var obj = { first: "John", last: "Doe" }; // Visit non-inherited enumerable keys Object.keys(obj).forEach(function(key) { console.log(key); });