difference between 'for (var i=0; i < x.length; i++)' and 'for (var iin x)'

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

    difference between 'for (var i=0; i < x.length; i++)' and 'for (var iin x)'

    Hi,

    I've come across the problem and I spent a remarkable amount of time
    debugging at the end of which I found the cause of the bug to be the
    following:

    var arr = ['a', 'b', 'c', 'd'];
    var arr2 = [];
    for (var i=0; i < arr.length; i++) {
    var elt = arr[i];
    arr2.push(elt);
    }
    // arr2 equals ["a", "b", "c", "d"]

    var arr = ['a', 'b', 'c', 'd'];
    var arr2 = [];
    for (var i in arr) {
    var elt = arr[i];
    arr2.push(elt);
    }
    // arr2 equals ["a", "b", "c", "d", function()]

    I thought that the second type of for loop is identical to the first
    one and just adds syntetic sugar. I guess I was wrong, can anyone shed
    some light on how the two loops are different?

    Thank you,
    Bálint
  • erdibalint

    #2
    Re: difference between 'for (var i=0; i &lt; x.length; i++)' and 'for(var i in x)'

    Thank you for your clear explanation. Synthetic sugar means a simpler
    (more concise or easier to retain) form of an expression that does the
    same (has the same semantics) as the more complex one.

    On Feb 20, 12:49 pm, RobG <rg...@iinet.ne t.auwrote:
    "syntactic sugar"?
    >

    Comment

    Working...