【问题标题】:TypeScript: how to add multiple elements to an array of the same valuesTypeScript:如何将多个元素添加到具有相同值的数组中
【发布时间】:2022-11-02 02:38:20
【问题描述】:

我想将多个具有相同值的元素添加到对象数组中,例如“.push()”,但有一个计数。我知道我可以做 array.push(a, b, c),但我希望能够做类似的事情:

person {
firstName: string;
lastName: string;
age: number;
}

people: Person[];
numberPeople: number;

// some calculation to generate numberPeople, example: 23

person.push( {firstName: '', lastName: 'Smith', age: 0}, NumberPeople)

我知道我可以使用循环结构(for (i=0; i<NumberPeople;i++) person.push),但这很麻烦。 有没有更简单的方法?我对 JavaScript 和 TypeScript 比较陌生。

我试过 .fill() 但这不允许我指定值。

谢谢,

我知道我可以创建自己的函数( mpush(obj, count) ),但如果有的话,我宁愿使用更优雅和标准的东西。

【问题讨论】:

  • 你想多次推送相同的值吗?
  • 您要求的是 JavaScript 中的类似数据库的功能。如果您使用的是 SQL 数据库,则可以使用诸如 countcollategroup by 之类的 sql 命令

标签: javascript arrays typescript


【解决方案1】:

您可以使用内置的fill() 方法,首先创建一个大小合适的Array,然后用一个值多次填充它。

interface person {
  firstName: string;
  lastName: string;
  age: number;
}

const samplePerson = {firstName: '', lastName: 'Smith', age: 0}

const people = Array(numberPeople).fill(samplePerson)

【讨论】:

  • 请记住,这会用相同的引用填充数组......所以如果你修改数组中的一个人,你就是在修改每个人。
猜你喜欢
  • 2021-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-14
  • 2022-01-18
  • 2022-01-04
相关资源
最近更新 更多