有没有更紧凑的方法来声明对象数组?

问题描述 投票:0回答:1

我是一名 C# 开发人员,在需要时使用 JavaScript。

有没有更紧凑的方式来编写以下内容?每件商品都需要重复每个成员的名字吗?

let cars = [
  {
    "color": "purple",
    "type": "minivan",
    "registration": new Date('2017-01-03'),
    "capacity": 7
  },
  {
    "color": "red",
    "type": "station wagon",
    "registration": new Date('2018-03-03'),
    "capacity": 5
  },
  {
    ...
  },
]
javascript javascript-objects
1个回答
0
投票

你可以使用工厂函数吗:

function createCar(color, type, registration, capacity) {
  return {
    color,
    type,
    registration: new Date(registration),
    capacity,
  };
}
let cars = [
  createCar("purple", "minivan", "2017-01-03", 7),
  createCar("red", "station wagon", "2018-03-03", 5),
];
© www.soinside.com 2019 - 2024. All rights reserved.