Example: Iterate an Array as an Object

by dshilkret

JavaScript

/* Firebug console required */

// simple array
var myObj = {"extension":["docx","pdf"]};//[1, 2, 3, 4, 5];

// instanceof tests
if (myObj instanceof Array) {
    alert("is Array");
};
if (myObj instanceof Object) {
    alert("is Object");
};

// print array to console
console.log(myObj);

// add a method to the Array class (Array of numbers expected)
Array.prototype.max = function() {
    var max = this[0];
    for (var i = 1; i < this.length; i++) {
        max = (this[i] > max) ? this[i] : max;
    }
    return max;
}

// alert max value of array
alert("Max is: "+myObj.max());

// iterate myObj properites - (alert only non-function, i.e. array members)
for (var key in myObj) {
    console.log("Key:" + key + " / Value: " + myObj[key] + " / Type: " + typeof myObj[key]);
    if (typeof myObj[key] != "function") {
        alert(myObj[key]);
    }
}