Page 1 of 1
javascript foreach equivalent?
#4
Posted 25 January 2006 - 10:13 PM
Nash12, on May 7 2005, 04:28 AM, said:
Unlike PHP there is no foreach-construct in Javascript, only "for" as Gornakle showed you. 
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]);
}So there you go, and it's incredibly useful.
~Some random guy on the internet
#8
Posted 24 April 2006 - 06:22 PM
justsomeguy, on Jan 25 2006, 11:13 PM, said:
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.
As all javascript objects are really just associative arrays, there is a foreach like syntax for the 'for' construct.
Thanks. And now for something a bit harder: is it possible to use a 'for' statement for listing all the field names/values in a form?
#9
Posted 06 May 2006 - 02:26 PM
hextreme, on Apr 24 2006, 06:22 PM, said:
Thanks. And now for something a bit harder: is it possible to use a 'for' statement for listing all the field names/values in a form?
I use it all the time. Check it out:
<script>
function showVals() {
theForm = document.getElementById('testing');
theStr = '';
for (i=0; i < theForm.elements.length; i++) {
ele = theForm.elements[i];
theStr += ele.name + ' : ' + ele.value + "\n";
}
alert (theStr);
}
</script>
<form id="testing">
<input type="text" name="namers" value="Namers Test!"/>
<input type="text" name="password" value="Password Test!"/>
<input type="button" onclick="showVals(); return false;" name="button" value="Display Values"/>
</form>
Page 1 of 1

Sign In
Register
Help



MultiQuote




