JavaScript for…in vs for

前端 未结 22 1135
悲哀的现实
悲哀的现实 2020-11-22 07:15

Do you think there is a big difference in for...in and for loops? What kind of \"for\" do you prefer to use and why?

Let\'s say we have an array of associative array

相关标签:
22条回答
  • 2020-11-22 07:18

    Although they both are very much alike there is a minor difference :

    var array = ["a", "b", "c"];
    array["abc"] = 123;
    console.log("Standard for loop:");
    for (var index = 0; index < array.length; index++)
    {
      console.log(" array[" + index + "] = " + array[index]); //Standard for loop
    }
    

    in this case the output is :

    STANDARD FOR LOOP:

    ARRAY[0] = A

    ARRAY[1] = B

    ARRAY[2] = C

    console.log("For-in loop:");
    for (var key in array)
    {
      console.log(" array[" + key + "] = " + array[key]); //For-in loop output
    }
    

    while in this case the output is:

    FOR-IN LOOP:

    ARRAY[1] = B

    ARRAY[2] = C

    ARRAY[10] = D

    ARRAY[ABC] = 123

    0 讨论(0)
  • 2020-11-22 07:19

    here is something i did.

    function foreach(o, f) {
     for(var i = 0; i < o.length; i++) { // simple for loop
      f(o[i], i); // execute a function and make the obj, objIndex available
     }
    }
    

    this is how you would use it
    this will work on arrays and objects( such as a list of HTML elements )

    foreach(o, function(obj, i) { // for each obj in o
      alert(obj); // obj
      alert(i); // obj index
      /*
        say if you were dealing with an html element may be you have a collection of divs
      */
      if(typeof obj == 'object') { 
       obj.style.marginLeft = '20px';
      }
    });
    

    I just made this so I'm open to suggestions :)

    0 讨论(0)
  • 2020-11-22 07:20

    FYI - jQuery Users


    jQuery's each(callback) method uses for( ; ; ) loop by default, and will use for( in ) only if the length is undefined.

    Therefore, I would say it is safe to assume the correct order when using this function.

    Example:

    $(['a','b','c']).each(function() {
        alert(this);
    });
    //Outputs "a" then "b" then "c"
    

    The downside of using this is that if you're doing some non UI logic, your functions will be less portable to other frameworks. The each() function is probably best reserved for use with jQuery selectors and for( ; ; ) might be advisable otherwise.


    0 讨论(0)
  • 2020-11-22 07:20

    With for (var i in myArray) you can loop over objects too, i will contain the key name and you can access the property via myArray[i]. Additionaly, any methods you will have added to the object will be included in the loop, too, i.e., if you use any external framework like jQuery or prototype, or if you add methods to object prototypes directly, at one point i will point to those methods.

    0 讨论(0)
  • 2020-11-22 07:20

    For in loops on Arrays is not compatible with Prototype. If you think you might need to use that library in the future, it would make sense to stick to for loops.

    http://www.prototypejs.org/api/array

    0 讨论(0)
  • 2020-11-22 07:20

    Be careful!!! I am using Chrome 22.0 in Mac OS and I am having problem with the for each syntax.

    I do not know if this is a browser issue, javascript issue or some error in the code, but it is VERY strange. Outside of the object it works perfectly.

    var MyTest = {
        a:string = "a",
        b:string = "b"
    };
    
    myfunction = function(dicts) {
        for (var dict in dicts) {
            alert(dict);
            alert(typeof dict); // print 'string' (incorrect)
        }
    
        for (var i = 0; i < dicts.length; i++) {
            alert(dicts[i]);
            alert(typeof dicts[i]); // print 'object' (correct, it must be {abc: "xyz"})
        }
    };
    
    MyObj = function() {
        this.aaa = function() {
            myfunction([MyTest]);
        };
    };
    new MyObj().aaa(); // This does not work
    
    myfunction([MyTest]); // This works
    
    0 讨论(0)
提交回复
热议问题