gpt4 book ai didi

javascript - 如何生成特定的字符串数组?

转载 作者:行者123 更新时间:2023-12-01 15:05:53 24 4
gpt4 key购买 nike

我有以下问题。我有一个数组:

const dates = ["19-June-2019", "18-June-2019", "17-June-2019", "16-June-2019", "14-June-2019"]

我需要生成一个日期数组,这些日期在我指的是行中的日期之后。所以:

const datesInRow = ["19-June-2019", "18-June-2019", "17-June-2019", "16-June-2019"]

这是我的初始函数:(isAfter function = date-fns)

 function numberOfDaysInRow(arr) {
if (arr.length === 1) return arr;
let numberOfDaysInRowArr = [];
for (let i = 0; i < arr.length; i++) {
if (isAfter(new Date(arr[i]), new Date(arr[i + 1]))) {
numberOfDaysInRowArr.push(arr[i]);
}
}
return numberOfDaysInRowArr;
}

这只返回部分答案。例如,如果我在数组中只有两个字符串,如下所示:

const dates = ["19-June-2019", "18-June-2019"]

它会返回

["19-June-2019"]

这不是我想要的。

最佳答案

const dates = ["19-June-2019", "18-June-2019", "17-June-2019", "16-June-2019", "14-June-2019"]
const datesInRow = ["19-June-2019", "18-June-2019", "17-June-2019", "16-June-2019"]
const datesBroken = ["19-June-2019", "18-June-2019", "17-June-2019", "16-June-2019", "10-June-2019", "09-June-2019", "08-June-2019"]

function isAfter(date1, date2) {
return (date1.getTime() - date2.getTime()) == 86400000;
}

function numberOfDaysInRow(arr) {
if (arr.length === 1) return arr;
let numberOfDaysInRowArr = [arr[0]];
for (let i = 0; i < arr.length - 1; i++) {
if (isAfter(new Date(arr[i]), new Date(arr[i + 1]))) {
numberOfDaysInRowArr.push(arr[i + 1]);
} else {
i = arr.length - 1;
}
}
return numberOfDaysInRowArr;
}

console.log(numberOfDaysInRow(dates))
console.log(numberOfDaysInRow(datesInRow))
console.log(numberOfDaysInRow(datesBroken))

您应该使用 [arr[0]] 初始化 numberOfDaysInRowArr

然后循环 i 直到 arr.length - 1

此外,推送 arr[i + 1] 而不是 arr[i]

关于javascript - 如何生成特定的字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56674566/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com