Previous topic in this series: Inheritance without Classes
- A different beast
- Types and Type Conversion
- Scopes and Scope Chain
- Objects without Classes
- Inheritance without Classes
- Array, Map and the for..in loop (You are here)
- Literals and JSON
- Meta-Programming, Exceptions and Module Pattern
//Code- Array is an Object var evenNumbers = new Array(); evenNumbers.push(2); evenNumbers.push(4); evenNumbers.push(6); console.log(typeof(evenNumbers)); //object console.log(evenNumbers instanceof Array); //true var fruits = ['apple', 'banana', 'grapes']; //native, first class arrays console.log(typeof(fruits)); //object console.log(fruits instanceof Array); //true
The Array object has a rich set of utility methods – foreach, map, filter etc. See this page for a complete reference. Unfortunately, some of those methods are not cross-browser compatible. But those can be fixed by monkey patching the Array.prototype (we have seen how to do this in the end of topic-6). The same technique is often used to add even more utility methods to Arrays.
Note: Since arrays are objects, they are always passed by reference and not by value. See this for a sample code.
var matrix = [ [ 1, 2, 3, 4 ], [ 5, 6, 6, 8], [ 9, 10, 11, 12 ] ]; console.log(matrix); //11 console.log(matrix); //4
The astute reader can observe that, director is infact an object with some dynamically added properties. And value ‘lookup’ is infact simply getting the values for the properties.
We will see a full fledged practical, reusable Map implementation in the next page after understanding the for..in loop