[thelist] Tip: if it caught me...
Ben Henick
persist1 at io.com
Tue Nov 27 15:35:18 CST 2001
This is meant for you right-brained people out there. I've been writing
JavaScript from scratch for 3+ years, but I didn't figure out the cause of
my crashes (related to the following story) until just now...
<tip type="avoidable non-terminating loops in JavaScript" author="Ben
Henick">
Let's suppose that you've got an array:
Colors = new Array();
Colors[0] = "red";
Colors[1] = "orange";
Colors[2] = "yellow";
Colors[3] = "lime";
Colors[4] = "green";
Colors[5] = "chartreuse";
Colors[6] = "cyan";
Colors[7] = "teal";
Colors[8] = "blue";
Colors[9] = "purple";
Colors[10] = "magenta";
Colors[11] = "pink";
Now, let's suppose that you want to duplicate this data set and append it
to its source without specifying new elements explicitly. (This would
occur to a creative long before they'd think to use modulus later in
the script, for example - if my experience is any yardstick. *grin*)
The way to do this at first glance would appear to be:
(for i = Colors.length; i < (Colors.length * 2); i++)
{
Colors[i] = Colors[(i - Colors.length)];
}
except for one problem: JavaScript reevaluates Colors.length on each pass
through the loop.
Which means that you'll have a nose-pickin', serenity-destroyin',
browser-crashin' non-terminating loop.
So, before you start the for loop, you store the value of Array.length in
a variable...
It seems simple, but my failure to figure this out until now has affected
my entire approach to certain tasks over the years. I can't help but
think that I am not the first person to hit this particular brick wall of
logic.
</tip>
Cheers,
--
Ben Henick
Web Author At-Large Managing Editor
http://www.io.com/persist1/ http://www.digital-web.com/
persist1 at io.com bmh at digital-web.com
--
"Are you pondering what I'm pondering, Pinky?"
"I think so, Brain, but... (snort) no, no, it's too stupid."
"We will disguise ourselves as a cow."
"Oh!" (giggles) "That was it exactly!"
More information about the thelist
mailing list