SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Enthusiast
    Join Date
    Feb 2007
    Posts
    42
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Bourne shell or Tcl style loop in JavaScript?

    In Bourne shell, you can do
    Code:
    for x in `foo bar grill` ; do
       echo $x
    done
    and in Tcl I can do:

    Code:
    foreach e in { foo bar grill} {
       put $e
    }
    but in JavaScript, I end up doing:

    Code:
    var l = [ 'foo', 'bar', 'grill' ];
    for (var i in l) {
       var x = l[i];
       ... do something with x...
    }
    Is there an idiom for looping over a fixed list of things in JavaScript that doesn't require creating a var before the loop?

  2. #2
    SitePoint Guru Ruben K.'s Avatar
    Join Date
    Jun 2005
    Location
    Alkmaar, The Netherlands
    Posts
    693
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Javascript does not have this functionality by default, but libraries like prototype do

    http://www.prototypejs.org/api/enumerable/each

  3. #3
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You can define your own methods.
    This is one general pattern- each element of the array is used as the argument of a function passed in the first argument.
    If the return value is 'truthy' (or if you have a second paremeter of true) it is added to the new array returned.
    The function can do anything you like, and the return may be used somewhere, discarded, or replace the original array.

    Code:
    Array.prototype.doforAll= function(fun,boo){
    	var L= this.length,A= [], tem;
    	for(var i= 0; i< L; i++){
    		try{
    			tem= fun(this[i]);
    		}
    		catch(er){
    			tem= null;
    		}
    		if(tem|| boo=== true) A.push(tem);
    	}
    	return A;
    }
    or for objects, with an object return
    Code:
    function doforAll(obj,fun,boo){
    	var G= new obj.constructor(), tem, temp;
    	for (var p in obj) {
    		if (obj.hasOwnProperty(p)) {
    			tem= obj[p];			
    			temp= fun(tem);
    			if (temp || boo=== true) G[p]= temp;
    		}
    	}
    	return G;
    }


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •