Monday, January 24, 2011

There is no foreach in JavaScript, use for … in instead

Programmer should be familiar with command foreach, which function is to iterate item within array or collection. This command normally available on most language, vb, php, c, java. Unfortunately, there is no foreach on JavaScript, and I just notice that until few minutes writing this post. After some research and reading over the javascript manual, I found that for … in is replacement for foreach

for … in

This command basically will iterate any object within an array, but instead refer to it’s collection object this command would pass only the key for collection object.

Syntax:

for (variable in object)
statement
Example

Please pay more attention on bolded italic text


child_cities=states[selected_state];
for(var cityid in child_cities)
{
ddl_city.options.length++;
ddl_city.options[ddl_city.options.length-1].text=
child_cities[cityid].description;
ddl_city.options[ddl_city.options.length-1].value=
child_cities[cityid].cityid;
}

No comments:

Post a Comment