Javascript Loops examples

by Riffic

JavaScript

var myArr = [1, 'two', 3, '4'];
var myObj = {
    key1: 1,
    key2: 'two',
    'key3': 3,
    key4: '4'
};
var myObjMore = {
    key1: 1,
    key2: 'two',
    key3: 3,
    key4: '4',
    key5: function() {
        alert("key5 function");
    }
};
myObjMore.test = function() {
    alert('test function');
};

function TestObj() {
    this.key1 = 1;
    this.key2 = 'two';
    this.key3 = function() {
        usePrivateFunction();
    };

    function privateFunction() {
        alert("privateFunction");
    }
}
TestObj.staticLike = function() {
    alert('static function');
};
TestObj.prototype.set = function() {
    alert('set testObj');
};
var myObjTest = new TestObj();

for (var i = 0; i < myArr.length; i++) {
    console.log("Arr Loop1:", myArr[i]);
};
//Objects can't be iterated over like this
console.log("Obj: ", myObj);
for (var i = 0; i < myObj.length; i++) {
    console.log("Obj Loop1:", myArr[i]);
};
//Now "for in" loops
for (item in myArr) {
    //Whoa! Throws a tun of public functions at you. Note the item.
    console.log("Arr Loop2: item: ", item);
    console.log("Arr Loop2: result: ", myArr[item]);
};
for (item in myObj) {
    //Note item is always a string, however the result stays consistant
    console.log("Obj Loop2: item: ", item);
    console.log("Obj Loop2: result: ", myObj[item]);
};
for (item in myObjMore) {
    //Note how both key5 and test items show up. 
    console.log("Obj Loop3: item: ", item);
    console.log("Obj Loop3: result: ", myObjMore[item]);
};
for (item in myObjTest) {
    //This time we can't see the inner function
    //However we can see the prototype as this object iterator is over the instance not the class
    //If we use TestObj directly in the "for in" loop, we then could see the staticLike function,
    //but not the instance vars
    console.log("Obj Loop4: item: ", item);
    console.log("Obj Loop4: result: ", myObjTest[item]);
};
console.log("Obj: ", TestObj);
for (item in TestObj) {
    //Note how both key5 and...