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

后端 未结 11 1990
走了就别回头了
走了就别回头了 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:29

    For-in-loops iterate over properties of an Object. Don't use them for Arrays, even if they sometimes work.

    Object properties then have no index, they are all equal and not required to be run through in a determined order. If you want to count properties, you will have to set up the extra counter (as you did in your first example).

    loop over an Array:

    var a = [];
    for (var i=0; i

    loop over an Object:

    var o = {};
    for (var prop in o) {
        prop // is the property name
        o[prop] // is the property value - the item
    }
    

提交回复
热议问题