foreach in JavaScript

Actually that’s not true at all.
As all javascript objects are really just associative arrays, there is a foreach like syntax for the ‘for’ construct.
Without it it would be very hard to work with many common javascript objects.
It’s actually very simple to use and incredibly useful if you like associative arrays.

You just have to make sure to use it on an associative array and not an object.
Example below

Good (assuming Object has not been overloaded or extended):

var array = new Object(); //this is safe only if you can assure object has not been extended.
//use the below if Object has been extended
var array;

//everything below here works fine regardless of the two above cases
array[‘something’] = ‘yay’;
array[‘somethingelse’] = ‘more’;

for ( keyVar in array ) {
alert(array[keyVar]);
}

Bad:

var array = new Array(); //uh oh, array is an object which means it’s an associative array

//the below loop will actually give you results, despite never putting «values» into
//the array variable. This is because array has functions defined from the Array() object
//which will be grabbed by the keyVar since objects are really associative arrays
for ( keyVar in array ) {
alert(array[keyVar]);
}

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *