是否有一种在JavaScript ES6中初始化数组的功能方法? [英] Is there a functional way to init an array in JavaScript ES6?

查看:356
本文介绍了是否有一种在JavaScript ES6中初始化数组的功能方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我终于放弃并为循环写了一个来初始化一个简单的对象数组,其中每个对象都有一个递增的计数器( 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},...];

我希望有一个紧凑的语法,我可以把它放在我的返回声明上。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆