JavaScript for…in vs for

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

提交回复
热议问题