3

As title say, why can't I map a array which contain undefined item?

var foo = new Array(3);
// [ , , ]
var bar = [null, null, null];
// [null, null, null]

foo.map(function(val){return 'test'});
// [ , , ]
bar.map(function(val){return 'test'});
// ['test', 'test', 'test']

maybe the foolish question, but I really want to know the reason.

thanks.

L.Jovi
  • 1,631
  • 4
  • 22
  • 36
  • 3
    "Because the spec says so" – Quentin Feb 15 '16 at 10:36
  • 1
    *"It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value)."* - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map – deceze Feb 15 '16 at 10:38

2 Answers2

1

From the MDN:

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, including undefined. It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value).

Pablo Lozano
  • 10,122
  • 2
  • 38
  • 59
1

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Description:

callback is invoked only for indexes of the array which have assigned values, including undefined. It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value).

It’s not working because elements haven’t been assigned a value.

If you use

foo[0] = undefined;
foo[1] = undefined;
foo[2] = undefined;

then it’ll work.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
artm
  • 8,554
  • 3
  • 26
  • 43