【问题标题】:How to find the current number of the week with find function如何使用查找功能查找当前周数
【发布时间】:2021-10-10 05:56:11
【问题描述】:

我有门票对象,每张门票都有自己的日期:

tickets: [
                {
                    id: 0,
                    time: "09:45",
                    date: new Date("2021-01-01"),
                    name: "Swimming in the hillside pond",
                },
                {
                    id: 1,
                    time: "09:45",
                    date: new Date("2021-01-08"),
                    name: "Swimming in the hillside pond",
                },
            ],

所以我想做的是找到每张票的周数,但如果周数与当前的不同。例如,如果门票日期是 2021 年 1 月 1 日,则周数应为 1,如果是 08.01.2021,则应为 2。因此,如果我有 3 张门票并且这些门票的日期是 [01.01.2021 , 08.01.2021, 09.01.2021],我想要一个像 [1,2] 这样的数组。

为此,我创建了函数:

currentNumberOfWeek(tickets) {
            return tickets.find((ticket, result) => {
                const oneJan = new Date(ticket.date.getFullYear(), 0, 1);
                const numberOfDays = Math.floor((ticket.date - oneJan) / (24 * 60 * 60 * 1000));
                result = Math.ceil((ticket.date.getDay() + 1 + numberOfDays) / 7);
                console.log(result);
                return result;
            });
        },

但首先,它返回的是票证而不是结果,而且在控制台中它没有显示正确的星期数。

你能看一下吗? 谢谢...

【问题讨论】:

  • 这能回答你的问题吗? Get week of year in JavaScript like in PHP
  • 我相信您对这个问题的回答已经在这里:stackoverflow.com/questions/3280323/get-week-of-the-month
  • 没错,有一些解决方案,但正如我在问题中告诉你的那样,我在查找函数时也遇到了一些问题。所以我不知道如何返回结果。
  • 你永远不会在 .find 回调中返回任何东西,所以当然没有任何东西是匹配的 - 阅读如何在这个 documentation中使用 find >
  • find() 的回调函数的参数result 试图达到什么目的?第二个参数是每个迭代元素的索引,而不是对结果变量的引用。见Array.prototype.find()

标签: javascript date week-number


【解决方案1】:

如果您只想查找机票的周数

const tickets = [
    {
        id: 0,
        time: "09:45",
        date: new Date("2021-01-01"),
        name: "Swimming in the hillside pond",
    },
    {
        id: 1,
        time: "09:45",
        date: new Date("2021-01-08"),
        name: "Swimming in the hillside pond",
    },
    {
        id: 1,
        time: "09:45",
        date: new Date("2021-01-12"),
        name: "Swimming in the hillside pond",
    },
]


let result = new Set()

function currentNumberOfWeek(arr) {
  arr.forEach(t => {
    let res = getWeekNr(t.date)
    result.add(res)
  })
}

function getWeekNr (date) {
  const oneJan = new Date(date.getFullYear(), 0, 1);
  const numberOfDays = Math.floor((date - oneJan) / (24 * 60 * 60 * 1000));
  let weekNr = Math.ceil((date.getDay() + 1 + numberOfDays) / 7);
  return weekNr;
}
currentNumberOfWeek(tickets)
console.log([...result]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 2019-09-05
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多