如何在TypeScript中创建从1到N的数组? [英] How to create an array from 1 to N in TypeScript?

查看:631
本文介绍了如何在TypeScript中创建从1到N的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是创建一个从1到N的数组,并将其命名为 first_array ,然后将其与另一个数组(第二个数组),并用相同的长度创建新的数组对象,如下所示:

What I want to do is creating an array from 1 to N and call it first_array, then combining it with another array(second array) with the same length and make a new array object like below:

new_array = [
  {
    "name": "first_array[0]",
    "value": second_array[0]
  },
  {
    "name": "first_array[1]",
    "value": second_array[2]
  },
    "name": "first_array[2]",
    "value": second_array[2]

];


推荐答案

如果要从1到<$ c的数组$ c> N ,您可以创建长度为 N 的新数组,用填充值填充它,然后使用它们的索引填充值 .map

If you want an array from 1 to N, you can create a new array of length N, fill it with a filler value, then populate the values using their indices with .map.

例如:

const n = 10;
const myArray = new Array(n).fill(null).map((_, i) => i + 1);

,结果为 myArray

[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

但是,在这种情况下,如果仅将其与数组一起使用似乎就不需要该数组另一个数组。相反,您可以使用其他数组( second_array )中的索引作为名称 键的值。

However in this case, it seems you don't need that array if you're just using it alongside another array. Instead you can use the index from that other array (second_array) as values for the "name" key.

就像这样:

const newArray = secondArray.map((e, i) => ({
    name: i + 1,
    value: e,
}));

示例案例:

输入

const secondArray = [100, 200, 300];

结果(对于 newArray

[
  { name: 1, value: 100 },
  { name: 2, value: 200 },
  { name: 3, value: 300 }
]

这篇关于如何在TypeScript中创建从1到N的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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