gpt4 book ai didi

javascript - 在map函数中制作数组

转载 作者:行者123 更新时间:2023-12-02 21:28:34 25 4
gpt4 key购买 nike

当我在此循环中创建数组时,我的代码出现一些问题,其重复与之前相同且不正确

getTimeShiftPermission = (data) => {
const toDay = moment().format('[today] dddd')
let newData = []
if (data) {
let newItem = {}
data.map((i, index) => {
if (i.start !== '00:00' || i.end !== '23:59') {
console.log('index', index, i)
newItem.start = i.start
newItem.end = i.end
newItem.day = moment.weekdays(index)
newData.push(newItem)
} else if (i.start === "" || i.end === "") {
return []
}
})
console.log('newData', newData)
return newData
} else {
return []
}}

及其结果

0:{开始:“03:02”,结束:“14:51”,日期:“星期四”}
1:{开始:“03:02”,结束:“14:51”,日期:“星期四”}

最佳答案

newItem 正在被重用。这意味着每次在循环内进行更改时,都会覆盖数组中的每个值。因此,在循环结束时,所有对象都将等于最后一次迭代。

您可以在将新对象推送到数组时创建一个新对象:

newData.push({...newItem})

或者您可以将声明移动到循环内:

let newData = []
if (data) {
data.map((i, index) => {
if (i.start !== '00:00' || i.end !== '23:59') {
let newItem = {} // Move it here
newItem.start = i.start
newItem.end = i.end
newItem.day = moment.weekdays(index)
newData.push(newItem)
}
})
return newData
}

或者您可以修复您的 map ,使其按照预期的方式实际使用。为此,您应该同时使用 filtermap:

if (data) {
// Return the array directly
return data.filter((i => {
// If your condition passes, we will keep it
if (i.start !== '00:00' || i.end !== '23:59') {
return true;
}
// Else filter it out
return false
}).map((i, index) => ({ // Return a new object with your formatted values
start: i.start
end: i.end
day: moment.weekdays(index)
})
}

关于javascript - 在map函数中制作数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60676776/

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