Friday, September 14, 2012

JavaScript: Array vs. Objects

Regular Array Object/Associate Array
// regular array (add an optional integer argument to control array's size)
var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
//Create a direct instance of an object
personObj=new Object();
personObj.firstname="John";
personObj.lastname="Doe";
personObj.age=50;
personObj.eyecolor="blue";
// create literal array
var myCars=["Saab","Volvo","BMW"];
//create alternative syntax (using object literals): 
personObj = {firstname:"John", lastname:"Doe", age:50, eyecolor:"blue"};
// find total length of array
document.write(myCars.length);
// output: 3
Object.size = function(obj) {
   var size = 0, key;
   for (key in obj) {
     if (obj.hasOwnProperty(key)) size++;
   } 
   return size;
};
document.write(Object.size(personObj));
// output: 4
// print individual element of array
document.write(myCars[0]);
// output: Saab
document.write(personObj['firstname']);
// output: John
document.write(personObj.firstname);
// output: John
// print all elements of array
for(var x = 0; x < myCars.length; x++){
     document.write(myCars[x] + " ");
}
// output: Saab Volvo BMW
var x;
for (x in personObj) {
     document.write(personObj[x] + " ");
}
// output: John Doe 50 blue

Refer site:
http://www.w3schools.com/js/js_obj_array.asp
http://www.w3schools.com/js/js_objects.asp

4 comments: