javascript - forEach on a 'new Array' isn't doing what I expect -
i'm learning how use js higher-order functions (map, foreach, reduce, etc), , have stumbled confusion. i'm trying write simple 'range' function, can't seem populate output array. goal:
range(1, 4) // [1, 2, 3, 4]
i'm getting this:
[undefined × 4]
here code:
function range(num1, num2) { var rangearr = new array((num2 + 1) - num1); return rangearr.map(function(e, i, arr) {return arr[i] = num1 + i}); }
what missing here? far can tell problem appears have way i'm utilizing 'new array', beyond i'm lost.
oh, , here's part confuses me. works fine:
function bleck() { var blah = [1, 2, 3, 4]; var x = 'wtf'; return blah.map(function(e, i, arr) {return arr[i] = x}) } ["wtf", "wtf", "wtf", "wtf"]
thanks!!
the foreach
method iterates on the indices of array. interestingly enough, when create new array via new array(n)
, contains no indices @ all. instead, sets .length
property.
> var = new array(3); > console.info(a) [] > console.info([undefined, undefined, undefined]) [undefined, undefined, undefined]
mdn describes foreach
, , states:
foreach executes provided callback once each element of array assigned value. not invoked indexes have been deleted or elided.
here's neat technique array empty, existing, indices.
var = array.apply(null, array(3));
this works because .apply
"expands" elided elements proper arguments, , results ends being array(undefined, undefined, undefined)
.
Comments
Post a Comment