2

Why does the code bellow returns an array of undefined values and I don't see any logs?

var arr = new Array(10);
arr = arr.map(function () {
    console.log('kapa');
    return 1;
});
console.log(arr);
thefourtheye
  • 206,604
  • 43
  • 412
  • 459
kharandziuk
  • 9,273
  • 9
  • 51
  • 94

3 Answers3

3

You can use Array.apply

Array.apply(null, {length: 10}).map(function(){return 1})
legendar
  • 91
  • 5
-1

The map() method creates a new array with the results of calling a provided function on every element in this array.

You don't have elements if you call new Array[10]

You must do something like

var temp = [];
for(var i=0;i<10;i++){
    temp[i]=i;
}

Or in your case

var temp = new Array();
for(var i=0;i<10;i++){
    temp.push(i);
}
Razvan Dumitru
  • 8,710
  • 4
  • 29
  • 50
-1

Both the ECMAScript specification and the slightly more readable MDN description of .map() spell it out fairly clearly. The .map() callback is not called for empty values of the array (e.g. values that are undefined).

From the MDN description for .map():

map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes that are undefined, those which have been deleted or which have never been assigned values.

So, since var arr = new Array(10); creates an array with ten empty slots in it, there are no values in the array that .map() will call its callback for.

If you actually put values in the initial array, then you will see the desired result:

var arr = [0,1,2,3,4,5,6,7,8,9];
arr = arr.map(function() {
    return 1;
});
console.log(arr);    // [1,1,1,1,1,1,1,1,1,1]

Working demo: http://jsfiddle.net/jfriend00/9c0hmL2j/


For some further documentation on .map(), you can see the ECMAScript specification for Array.prototype.map. Steps 8b and 8c in that section of the spec describe how the callback to .map() will not be called if a given array property has no value.

jfriend00
  • 580,699
  • 78
  • 809
  • 825