What is the best way to do loops in JavaScript

前端 未结 9 1884
温柔的废话
温柔的废话 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:21

    I don't use it myself, but one of my colleagues uses this style:

    var myArray = [1,2,3,4];
    for (var i = 0, item; item = myArray[i]; ++i) {
        alert(item);
    }
    

    like Ash's answer, this will hit issues if you've got "falsey" values in your array. To avoid that problem change it to (item = myArray[i]) != undefined

提交回复
热议问题