Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why can't map 'undefined' array [duplicate]

Tags:

javascript

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.

like image 932
E_Jovi Avatar asked Dec 27 '25 16:12

E_Jovi


2 Answers

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.

like image 115
artm Avatar answered Dec 30 '25 04:12

artm


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).

like image 37
Pablo Lozano Avatar answered Dec 30 '25 05:12

Pablo Lozano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!