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

前端 未结 4 394
礼貌的吻别
礼貌的吻别 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条回答
  •  花落未央
    2021-01-18 10:17

    The problem is that map doesn't iterate undefined entries (*).

    I suggest using a for loop instead:

    var rangeArr = new Array((num2 + 1) - num1);
    for(var i=0; i<=num2-num1; ++i)
        rangeArr[i] = num1 + i;
    return rangeArr;
    

    (*) With undefined entries I mean rangeArr.hasOwnProperty(i) === false, not to be confused with rangeArr[i] === void 0.

提交回复
热议问题