[thelist] Tip: if it caught me...

Chris Blessing webguy at mail.rit.edu
Tue Nov 27 15:38:32 CST 2001


This is a common problem when dealing with array expansion, etc.  One reason
why I always (well, maybe 99% of the time ;)) store the array length in a
var (unless I want it to be ever in/decreasing).  Good tip!

Chris Blessing
webguy at mail.rit.edu
http://www.330i.net

> -----Original Message-----
> From: thelist-admin at lists.evolt.org
> [mailto:thelist-admin at lists.evolt.org]On Behalf Of Ben Henick
> Sent: Tuesday, November 27, 2001 4:36 PM
> To: thelist at lists.evolt.org
> Subject: [thelist] Tip: if it caught me...
>
>
> 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!"
>
>
> ---------------------------------------
> For unsubscribe and other options, including
> the Tip Harvester and archive of TheList go to:
> http://lists.evolt.org Workers of the Web, evolt !





More information about the thelist mailing list