for loop question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • cp

    #1

    for loop question


    in Perl I would write a for loop as :

    for $i ( 1..2 ) {
    print "<p>$i</p>";
    }

    which would output:
    <p>1</p>
    <p>2</p>

    In JavaScript I would write:

    for (var i=1;i<3;i++) {
    ...

    or is there an easier (or more idiomatic) way?

    --
    cp
  • Lasse Reichstein Nielsen

    #2
    Re: for loop question

    cp <cpryce@nospam. pryce.net> writes:
    [color=blue]
    > in Perl I would write a for loop as :
    >
    > for $i ( 1..2 ) {
    > print "<p>$i</p>";
    > }
    >[/color]
    ....[color=blue]
    > In JavaScript I would write:
    >
    > for (var i=1;i<3;i++) {
    > ...
    >
    > or is there an easier (or more idiomatic) way?[/color]

    There isn't.

    There is another use of "for" in Javascript, that is closer to the
    Perl version:
    for (var x in obj) { ... }
    It iterates through the properties of an object. Notice that it
    is different from Perl in that the variable "x" is bound to the
    *name* of the properties, not the value.

    So, in Perl

    my @arr = (1,4,7,9);
    for $i (@arr) {
    print "$i - ";
    }

    would print "1 - 4 - 7 - 9 - ", while in Javascript

    var arr = [1,4,7,9];
    for (var i in arr) {
    document.write( i+" - ");
    }

    would write "0 - 1 - 2 - 3 - ". To get the same effect as in Perl, use

    var arr = [1,4,7,9];
    for (var i in arr) {
    document.write( arr[i]+" - ");
    }

    (I bit me a lot when I started doing Javascript).
    /L
    --
    Lasse Reichstein Nielsen - lrn@hotpop.com
    DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
    'Faith without judgement merely degrades the spirit divine.'

    Comment

    • Douglas Crockford

      #3
      Re: for loop question

      > for $i ( 1..2 ) {[color=blue]
      > print "<p>$i</p>";
      > }
      >
      > which would output:
      > <p>1</p>
      > <p>2</p>
      >
      > In JavaScript I would write:
      >
      > for (var i=1;i<3;i++) {
      > ...
      >
      > or is there an easier (or more idiomatic) way?[/color]

      There should be, but there isn't. I don't think that the C control structures
      are suitable for a scripting language, but that's all you get in JavaScript.



      Comment

      Working...