Messing With Iterators
The for-in and for-each loops are convenient and likely to be the loops you use most. For this reason alone you should make sure you know what you can and can’t do with them. Here’s one thing I just found can save me some typing and some bloat.
Situations like this come up all the time:
// Loop over some relative URLs for each (var url:String in urls) { var temp:String = url; // Make relative URL absolute temp = "http://www.mysite.com/pages/" + url + "?"; // Add query string parameters for each (var query:Object in queries) { temp += query.key + "=" + query.val + "&"; } // Hack off the last "&" temp = temp.substr(0, temp.length-1); }
But do you need the temp variable or can you use url? Is it safe to change the iterator variable? The answer is a comforting and clean “yes”! Changing the iterator will not alter the iteration of the loop in any way.
With that in mind, why not start your week off by rewriting a for-in or for-each loop where you needlessly made a temporary variable? Then repent of temporary variables and write cleaner, less bloated loops from now on. :)
#1 by kutu on December 7th, 2009 ·
what’s about “&” between “key=val” ?
like this:
?key=val&key=val
#2 by jackson on December 7th, 2009 ·
Yep, I forgot the “&” between the key/value pairs. After exactly half a year, someone finally pointed it out! I’ve updated the article to fix it. Thanks for using the comments!