通过map函数初始化Array with Objects

时间:2017-02-08 10:10:28

标签: javascript

我不知道为什么这段代码不起作用:

Array(50).map(e => { e = {id: Math.random() , content: 'some_content'}; return e });

3 个答案:

答案 0 :(得分:1)

它当然会按照你的要求去做,而不是你想要它做什么。

问题在于map函数"is invoked only for indexes of the array which have assigned values, including undefined."调用Array(50)会创建50个空插槽,但不会分配给它们,因此地图不执行任何操作。

作为someone else suggested,您可以使用Array.from()快速创建包含undefined的50个元素的数组。

答案 1 :(得分:0)



var result = Array.apply(null, { length: 50 }).map(e => { e = {id: Math.random() , content: 'some_content'}; return e });
console.log(result);






  var result = [...Array(50)].map(e => { e = {id: Math.random() , content: 'some_content'}; return e });
    console.log(result);




答案 2 :(得分:0)

您可以使用Array.apply并将映射的返回值包装在括号中,以返回对象。



var array = Array.apply(null, { length: 50 }).map(_ => ({id: Math.random() , content: 'some_content'}));
console.log(array)