forEach on a 'new Array' isn't doing what I expect

前端 未结 4 512
礼貌的吻别
礼貌的吻别 2021-01-18 10:07

I\'m just learning how to use JS higher-order functions (map, forEach, reduce, etc), and have stumbled into confusion. I\'m trying to write a simple \'range\' function, but

4条回答
  •  Happy的楠姐
    2021-01-18 10:24

    The forEach method iterates over the indices of the array. Interestingly enough, when you create a new array via new Array(n), it contains no indices at all. Instead, it just sets its .length property.

    > var a = new Array(3);
    > console.info(a)
    []
    > console.info([undefined, undefined, undefined])
    [undefined, undefined, undefined]
    

    MDN describes forEach, and specifically states:

    forEach executes the provided callback once for each element of the array with an assigned value. It is not invoked for indexes which have been deleted or elided.

    Here's a neat technique to get an array with empty, but existing, indices.

    var a = Array.apply(null, Array(3));
    

    This works because .apply "expands" the elided elements into proper arguments, and the results ends up being something like Array(undefined, undefined, undefined).

提交回复
热议问题