Monday, October 12, 2015

Arrays 

JavaScript arrays are used to store multiple values in a single variable, which can hold more than one value at a time. Arrays are a special type of objects, So typeof operator in JavaScript returns "object" for arrays. Arrays use numbered indexes.  
Example: var names= ["Chanthan", "Jack", "Jhon"];
Arrays use numbers to access its "elements". For this example, names[0] returns Chanthan.

Objects

Objects use names to access its "members". Objects use named indexes.
Example: var person = {firstName:"Chanthan", lastName:"Ratn", age:25};
For this example, person.firstName returns Chanthan.


In array, If you use a named index, JavaScript will redefine the array to a standard object. After that, all array methods and properties will produce incorrect results.
Example:
var size = person.length; // person.length will return 0 
var name= person[0]; // person[0] will return undefined

So how to get the length of a object  in JavaScript object (that is, associative array)
Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};
//get the length of array object
var size = Object.size(array);

So, When to Use Arrays. When to use Objects.
  1. JavaScript doesn't support associative arrays.
  2. Use objects when you want the element names to be strings (text).
  3. Use arrays when you want the element names to be numbers.

0 comments:

Post a Comment

Popular Posts

Recent Posts

Unordered List

Text Widget

Powered by Blogger.

Popular Posts