gpt4 book ai didi

javascript - 如何使用 moment.js 和 ES6 创建小时 + 分钟数组?

转载 作者:行者123 更新时间:2023-12-01 15:52:49 27 4
gpt4 key购买 nike

我正在尝试使用 moment.js 和 ES6 在一天中以 30 分钟的间隔创建一个小时数组。

例子:let hours = ["12:00 AM", "12:30 AM", "1:00 AM", "1:30 AM", ..., "11:30 PM"]
我已经有了这个for功能:

someFunction () {
const items = []
for (let hour = 0; hour < 24; hour++) {
items.push(moment({ hour }).format('h:mm A'))
items.push(moment({ hour, minute: 30 }).format('h:mm A'))
}
return items
}

但我想让它更像 ES6。

我已经做到了这一点:
someFunction () {
let timeSlots = new Array(24).fill().map((acc, index) => {
let items = []
items.push(moment( index ).format('h:mm A'))
items.push(moment({ index, minute: 30 }).format('h:mm A'))
})
return timeSlots
}

但它输出:
["1:00 AM", "12:30 AM", "1:00 AM", "12:30 AM", "1:00 AM", "12:30 AM", "1:00 AM", "12:30 AM", "1:00 AM", "12:30 AM", "1:00 AM", "12:30 AM", ...]

最佳答案

function someFunction () {
const items = [];
new Array(24).fill().forEach((acc, index) => {
items.push(moment( {hour: index} ).format('h:mm A'));
items.push(moment({ hour: index, minute: 30 }).format('h:mm A'));
})
return items;
}

关于javascript - 如何使用 moment.js 和 ES6 创建小时 + 分钟数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53867790/

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