【问题标题】:How to add number 7 and smaller numbers to an array?如何将数字 7 和更小的数字添加到数组中?
【发布时间】:2020-08-26 09:17:34
【问题描述】:

我的问题是我想获取 2020 年的所有月份,即 1 月、2 月、Marts、4 月、5 月、6 月、7 月和 8 月,并将它们添加到数组中。

当我使用下面的代码时,我在可变月份中得到数字 7,这意味着它是八月。现在我想将 7、6、5、4、3、2、1、0 添加到数组中。我该怎么做?

const d = new Date(); const month = d.getMonth();

我是打字稿的新手,希望有人能够帮助我。提前致谢。

【问题讨论】:

    标签: arrays typescript date numbers


    【解决方案1】:

    这不是 Typescript 特定的,可以使用纯 javascript 完成。 如果 getMonth 是 7 而你想要 [0, 1, 2, 3, 4, 5, 6, 7] 那么你可以使用这个:

    const d = new Date();
    const month = d.getMonth();
    const monthArray = Array.from(Array(month + 1).keys());
    

    我使用了以下参考:https://stackoverflow.com/a/33352604/9124424

    【讨论】:

      【解决方案2】:

      使用简单的for循环和while循环在数组中输入元素的问题代码](https://i.stack.imgur.com/aJRkX.jpg)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-08
        • 1970-01-01
        • 2022-01-13
        • 1970-01-01
        • 2018-04-25
        相关资源
        最近更新 更多