What is JavaScript for(i=0; item=array[i++]; ) in Python?

12 views
Skip to first unread message

Jonathan Fine

unread,
May 2, 2010, 3:08:30 AM5/2/10
to JavaScript for Python programmers
A common and useful JavaScript idiom is

   js> array = [4, 5, 9]
   4,5,9
   js> var i, item;
   js> for(i=0; item=array[i++]; ) { print(item) }
   4
   5
   9
   js>

It's the quickest way to loop through the items in an array, all of whose entries are 'truish'.

BTW, one can then use
   js> i == array.length + 1
  true
to check to see if we stopped early, say because the array contains a zero.

The corresponding Python idiom is
    for item in array:
        print item
and often the JavaScript above gives the desired translation (but not if array is in fact a dict object).

This led me to thinking:  What do we write in Python to get '++i' in the JavaScript?  Recall that Python does not have the '++' operator.

And the answer is quite simple.  One writes 'rinc(x)' (for right increment, or possibly call it something else).  It would not be hard to add that to my jsinpy.py toy.

In fact, the Python for the JavaScript
    var i;
    for(i=0; item=array[i++]; )
is
    i = 0
    while 1:
        item = array[rinc(i)]
        if not item: break

--
Jonathan

--
You received this message because you are subscribed to the Google Groups "JavaScript for Python programmers" group.
To post to this group, send an email to js...@googlegroups.com.
To unsubscribe from this group, send email to js4py+un...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/js4py?hl=en-GB.
Reply all
Reply to author
Forward
0 new messages