Главная > Компьютеры > foreach in JavaScript

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]);
}

Рубрики:Компьютеры Метки: , , ,
  1. Комментариев нет.
  1. No trackbacks yet.

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

Please log in using one of these methods to post your comment:

Логотип WordPress.com

Для комментария используется ваша учётная запись WordPress.com. Выход / Изменить )

Фотография Twitter

Для комментария используется ваша учётная запись Twitter. Выход / Изменить )

Фотография Facebook

Для комментария используется ваша учётная запись Facebook. Выход / Изменить )

Google+ photo

Для комментария используется ваша учётная запись Google+. Выход / Изменить )

Connecting to %s

%d такие блоггеры, как: