Thomas 'PointedEars' Lahn said the following on 2/6/2006 10:39 AM:
Randy Webb wrote:
Fabian Vilers said the following on 2/6/2006 7:48 AM: var my_array = new Array();
// populate array
var my_array_length = my_array.length
for (i = 0; index < my_array_length ; index++)
{
// do something with my_array[index]
}
That one will fail if the array is what is called "sparse" where every
element is not defined:
my_array[1] = "something" ;
my_array[4] = "no 2 or 3";
No, it will not.
Yes, it will fail in the sense that it will not do what you would think
it would do. Had it not been for your desire to be pedantic about my
response you would not have felt it necessary to point that out. What
you didn't point out was the use of different variables in the for loop
though. The i=0 in the example above is unneeded.
So, let me phrase it in a way that you might be able to understand it,
given your displayed inability to comprehend simple English:
A for-loop will not perform as expected if it is used on a sparse array.
It will loop over undefined array elements and that could possibly skew
any calculations/procedures you may attempt to perform using those array
entries.
Now, just for you, a code snippet that displays where it will "fail".
<script type="text/javascript">
var my_array = new Array()
my_array[0] = 1
my_array[1000] = 2
var my_array_length = my_array.length
var counter = 0
for (var index = 0; index < my_array_length ; index++)
{counter = counter + my_array[index]}
alert(counter)
</script>
The desired results would be 3, the actual result will be NaN.
Also, not the lack of any semi-colons at the end of any statement in my
code other than in the for loop definition.
BTW, in the future, I would appreciate it if you kept your pedantic
bullshit noise creating post to yourself.
--
Randy
comp.lang.javas cript FAQ -
http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices -
http://www.JavascriptToolbox.com/bestpractices/