Get loop counter/index using for…of syntax in JavaScript

后端 未结 11 1961
走了就别回头了
走了就别回头了 2020-11-28 00:55

Caution:

question still applies to for…of loops.> Don\'t use for…in to iterate over an Array, use it

11条回答
  •  余生分开走
    2020-11-28 01:27

    As others have said, you shouldn't be using for..in to iterate over an array.

    for ( var i = 0, len = myArray.length; i < len; i++ ) { ... }
    

    If you want cleaner syntax, you could use forEach:

    myArray.forEach( function ( val, i ) { ... } );
    

    If you want to use this method, make sure that you include the ES5 shim to add support for older browsers.

提交回复
热议问题