【问题标题】:js array push results returns only length of iterations [moment js & angular]js 数组推送结果仅返回迭代长度 [moment js & angular]
【发布时间】:2019-01-30 02:18:52
【问题描述】:

我有一个函数可以在一个月内迭代几天。从那里我用 ngFor 在我的 html 中显示它们。我想将日期数字显示为文本,并将日期名称(星期一、星期二、星期三等)显示为每天的课程。

monthDays = []; // global variable

  getDaysInMonth(month, year) {
    var date = new Date(year, month);
    var days = []; // 1,2,3
    var daysName = []; // mon, tue, wed
    while (date.getMonth() === month) {
      this.monthDays.push({
        days: days.push(moment(date).format("D")),
        daysName: daysName.push(moment(date).format("M"))
      })
      date.setDate(date.getDate() + 1);
    }
    console.log(this.monthDays);
  }

因为我需要两个属性(天和天名),所以我将它们推送到一个 monthDays 全局变量数组中,但结果只是月份的数字

Array(31) // I.e Jan getDaysInMonth(1,2019)
0: {days: 1, daysName: 1} // should be days: 1 , daysName: 'Tue'
1: {days: 2, daysName: 2} // should be days: 2 , daysName: 'Wed'

所以我可以在我的 html 中像这样使用对象

<p *ngFor="let x of monthDays" class="{{x.daysName}}" >{{ x.days }}</p>

任何帮助或推动正确的方向都会很棒。

【问题讨论】:

  • 最好在询问为什么方法没有按预期工作之前检查文档 - push 返回数组的新长度,而不是变异数组。

标签: javascript arrays angular momentjs


【解决方案1】:

因为push 返回数组的新长度Array pushdaysdaysName 是数组的长度。我认为您想要获取具有 2 个属性的数组对象是 day 和 dayname。试试看:

monthDays = []; // global variable

getDaysInMonth(month, year) {
    var date = new Date(year, month);
    var days = []; // 1,2,3
    var daysName = []; // mon, tue, wed
    while (date.getMonth() === month) {
        this.monthDays.push({
            days: moment(date).format("D"),
            daysName: moment(date).format("dddd")
        })
        date.setDate(date.getDate() + 1);
    }
    console.log(this.monthDays);
}

【讨论】:

  • 谢谢!我看到了我的问题,我知道 push 返回了长度但不明白为什么,我一直试图将对象中的 days 和 daysName 分配给局部变量,而不是将它们设置为属性。
猜你喜欢
  • 1970-01-01
  • 2018-02-10
  • 1970-01-01
  • 2020-05-06
  • 2022-08-23
  • 2014-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多