PDA

View Full Version : How to get first/last elements of an associative array?



jlizarraga
10-24-2008, 10:32 PM
Hi all,

How do you find the first and last elements of an associative array?

Seems simple, but it escapes me.

Thanks!

Trinithis
10-24-2008, 10:37 PM
Define "first" and "last".

You could try using a for-in loop:



for(var x in obj) {
if(obj.hasOwnProperty(x))
alert(x + ":" + obj[x]);
}

jscheuer1
10-25-2008, 09:35 AM
There are no elements in a javascript associative array.


var assocArray = new Array();
assocArray['bob'] = null;
assocArray['joe'] = 2000;
assocArray['albrecht'] = 'E = Mc squared';

// show 'first' value stored
;(function(){
for (var p in assocArray)
if(assocArray.hasOwnProperty(p)){
alert("'first\' key: " + p + ", value's: " + assocArray[p]);
break;
};
})();

// show 'last' value stored
;(function(){
var pv;
for (var p in assocArray)
if(assocArray.hasOwnProperty(p))
pv = "'last' key: " + p + ", value's: " + assocArray[p];
alert(pv);
})();

Notes: Often javascript Objects are thought of as associative arrays. They would act the same in the above code. They are structured as associative arrays. However, I chose to use an actual array to illustrate a point. The above array has a length of 0, so technically has no first or last (or any) elements. It has properties. Javascript Arrays are also javascript Objects, but javascript Objects are not necessarily (strictly speaking are never) javascript Arrays. If created with the Object constructor, they have no intrinsic length property (undefined).