javascript - .map not working as expected on uninitiated array - Stack Overflow

Using .map() on an array full of undefined values (eg new Array(10)) will always return an array of the

Using .map() on an array full of undefined values (eg new Array(10)) will always return an array of the same length with undefined values, no matter what you return.

new Array(10).map(function(){return 5;});

will return a new array filled with 10x undefined. Why does this happen?

Using .map() on an array full of undefined values (eg new Array(10)) will always return an array of the same length with undefined values, no matter what you return.

new Array(10).map(function(){return 5;});

will return a new array filled with 10x undefined. Why does this happen?

Share Improve this question asked Apr 18, 2016 at 12:31 René RothRené Roth 2,1461 gold badge20 silver badges25 bronze badges 3
  • FYI this happens in both Google Chrome as well as NodeJS, so I think it's not an implementation-specific bug. – René Roth Commented Apr 18, 2016 at 12:32
  • 1 It's not a bug if it's documented :) – Tudor Constantin Commented Apr 18, 2016 at 12:47
  • @TudorConstantin well, if we're being pedantic, I never said it is a bug :) – René Roth Commented Jul 1, 2023 at 20:42
Add a ment  | 

4 Answers 4

Reset to default 4

Because when you define an array like that, the spaces for values are empty slots and are not iterated over by map() or any of its friends.

There is Array.prototype.fill() (in ES6) which can be used to set values on that array.

You could use

var array = Array.apply(null, { length: 10 }).map(function(){ return 5; });

var array = Array.apply(null, { length: 10 }).map(function() { return 5; });
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');

from the fine manual:

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

new Array(10)

creates missing elements, if that makes any sense.

Like this one:

var b=new Array();
b[30] = 1;
var c = b.map(function(){return 5;});

> [undefined × 30, 5]

There's an answer for this here: https://stackoverflow./a/5501711/6206601. Look at the top ment for further clarification.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744836575a4596298.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信