forEach returns undefined

2020-05-10 12:17发布

问题:

I'm using moment.js and trying to process a date using that code

function toISOdate (date) {
    return moment(date, 'DD.MM.YYYY').toISOString()
}
function toMomentDate (date) {
    return moment(date)
}


let input = "25.11.2017-25.11.2017"
let dateArray = input
                    .split('-')
                    .forEach(toISOdate)
console.log(dateArray, input)

But the problem is that dateArray returns undefined. Maybe it's very obvious mistake, but I can't find it.

回答1:

Use map() that returns:

A new array with each element being the result of the callback function.

instead of forEach(). forEach doesn't return anything (undefined).