Be careful with for .. in .. loops when you''re treating objects as
associative arrays.
for .. in .. iterates over all properties, which include functions
the object has.
So, having an object like this:
var obj = {
a: 1,
b: 2,
test: function() { }
}
for .. in ... will iterate over a, b, and test.
A "safer" way to call for .. in .. goes like this:
for (p in obj) if(typeof obj[p] != ''function) alert(p + ‘=’ + obj[p]);
Btw, it would probably ne a nice thing to have something like that in
Prototype, so that this could be called like so:
MyObj.each( function(k,v) { /* do somehting */ } )
for designated "Hash" variables:
$H({ a:1, b:2 }).each( function(k,v) { ... });
Any thoughts?
Cheers,
Thomas
Am 11.11.2005 um 16:35 schrieb Gregory Hill:
> Can’t you just do this? It’s built into javascript:
>
>
> for (key in arrayname) {
> alert(key + ‘=’ + arrayname[key]);
>
> }
>
>
>
>
>
> From:
rails-spinoffs-bounces-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org
[mailto:rails-
> spinoffs-bounces-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org] On
Behalf Of Stich, Josef
> Sent: Friday, November 11, 2005 3:32 AM
> To: rails-spinoffs-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org
> Subject: [Rails-spinoffs] array.each() on associative array?
>
>
>
> Hi List!
>
>
>
> Is there a way to iterate through an associative array when
> prototype.js is used?
>
>
>
>
>
>
>
> arrayname.each(function (i) {
>
> alert(i);
>
> });
>
> seems to work only for numeric arrays.
>
>
>
>
>
> Thanks, Josef Stich
>
>
>
> _______________________________________________
> Rails-spinoffs mailing list
> Rails-spinoffs-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org
> http://lists.rubyonrails.org/mailman/listinfo/rails-spinoffs