JavaScript for…in vs for

前端 未结 22 1194
悲哀的现实
悲哀的现实 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: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.


提交回复
热议问题