在 JavaScript ES6 中是否有一种函数式的方式来初始化一个数组? [英] Is there a functional way to init an array in JavaScript ES6?
问题描述
我终于放弃了,写了一个 for
循环来初始化一个简单的对象数组,其中每个对象都有一个递增的计数器 (id
) 作为对象的属性.换句话说,我只想:
I finally gave up and wrote a for
loop to initialize a simple array of objects where each object has an incremented counter (id
) as an attribute of the object. In other words, I just want:
var sampleData = [{id: 1},{id: 2},...];
我希望有一个紧凑的语法,我可以把它放在我的 return 语句中.
I was hoping for a compact syntax I could just put on my return statement.
let sampleData = [];
for (var p = 0; p < 25; p++){
sampleData.push({id: p});
}
return {
data: sampleData,
isLoading: true
};
推荐答案
Array.from()
是一个很好的方法.您可以传递一个 {length: somlength}
对象或其他一些类似数组的对象和一个定义每个项目的函数.该函数的第一个参数(调用它 _
只是为了表明它没有被使用)将是我们传入的数组中的项(但我们只传入了一个长度,所以它没有多大意义),第二个i
是索引,用于你的id
:
Array.from()
is a nice way to do this. You can pass a {length: somlength}
object or some other array-like object and a function that defines each item. The first argument (calling it _
just to indicate it's not used) to that function would be the item from an array we passed in (but we only passed in a length so it doesn't mean much), the second i
is the index, which is used for your id
:
let sampleData = Array.from({length: 10}, (_, id) => ({id}))
console.log(sampleData)
这篇关于在 JavaScript ES6 中是否有一种函数式的方式来初始化一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!