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.
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Description:
callbackis invoked only for indexes of the array which have assigned values, includingundefined. 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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With