Difference between for vs for var in javascript

This question already has an answer here:

  • For-each over an array in JavaScript? 23 answers

  • Well, for(i in x) works with both, arrays and objects

    var x = [1, 2, 3];
    for(var i in x) console.log(x[i]);
    
    var o = {1:1, 2:2, 3:3};
    for(var i in o) console.log(o[i]);
    

    While for(;;) works only with arrays

    var x = [1, 2, 3];
    for(var i=0; i<x.length; i++) console.log(x[i]);
    
    var o = {1:1, 2:2, 3:3};
    for(var i=0; i<o.length; i++) console.log(x[i]); // returns undefined because object o doesn't have property length
    

    But you could use Object.keys to get array of keys of object

    var o    = {1:1, 2:2, 3:3};
    var keys = Object.keys(o);
    for(var i=0; i<keys.length; i++) console.log(o[keys[i]]);
    

    Common practice is to use for(i in x) for objects and for(;;) for arrays


    Like it says in the MDN documentation:

    The for...in statement iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.

    Your first statement is used for an array, while the second is used to get all keys of an object.


    Already there are discussions and answers of this question.

    Refer Question to know the difference.

    The for...in statement iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.

    The for statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement or a set of statements executed in the loop.

    链接地址: http://www.djcxy.com/p/12066.html

    上一篇: 将一些PHP代码转换为javascript(相当于foreach)

    下一篇: javascript中var和var之间的区别