[removed] hiding prototype methods in for loop?

后端 未结 6 1760
攒了一身酷
攒了一身酷 2020-12-01 05:14

So lets say I\'ve added some prototype methods to the Array class:



Array.prototype.containsKey = function(obj) {
    for(var key in this)
        if (key =         


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 05:41

    For high-performance iteration over JavaScript arrays, use either a for or while loop. Nicholas Zakas discusses the most-performant options for iterating over arrays in his Tech Talk Speed Up Your JavaScript.

    Your best bet is probably something like this:

    for (var i = collection.length - 1; i >= 0; i--) {
      if (obj == collection[i]) return true;
    }
    

    This approach will be peform best for a few reasons:

    • Only a single local variable is allocated
    • The collection's length property is only accessed once, at the initialization of the loop
    • Each iteration, a local is compared to a constant (i >= 0) instead of to another variable

提交回复
热议问题