What is the best way to do loops in JavaScript

前端 未结 9 1890
温柔的废话
温柔的废话 2020-12-13 00:35

I have stumbled into several methods of looping in JavaScript, what I like the most is:

for(var i = 0; i < a.length; i++){
    var element = a[i];
}
         


        
9条回答
  •  一向
    一向 (楼主)
    2020-12-13 01:16

    Small improvement to the original, to only calculate the array size once:

    for(var i = 0, len = a.length; i < len; i++){ var element = a[i]; }
    

    Also, I see a lot of for..in loops. Though keep in mind that it's not technically kosher, and will cause problems with Prototype specifically:

    for (i in a) { var element = a[i]; }
    

提交回复
热议问题