gpt4 book ai didi

javascript - 理解 javascript return 语句为什么返回 undefined

转载 作者:行者123 更新时间:2023-11-30 11:20:06 25 4
gpt4 key购买 nike

我正在处理下面的 javascript 代码,有人可以解释为什么下面的代码输出是 undefined 吗?

给定一年,根据该年的官方俄罗斯日历找出该年的 256th 日的日期。

然后以dd.mm.yyyy格式打印。

function solve(year) {
if (year < 1700 || year > 2700) {
return false;
} else if (year >= 1700 && year <= 1917) {
if (year % 4 === 0) {
var days = [31, 29, 31, 30, 31, 30, 31, 31];
calculate(days)
`enter code here`
}
var days = [31, 28, 31, 30, 31, 30, 31, 31];
calculate(days)
} else if (year > 1918 && year <= 2700) {
if (year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0)) {
var days = [31, 29, 31, 30, 31, 30, 31, 31];
calculate(days)
}
var days = [31, 28, 31, 30, 31, 30, 31, 31];
calculate(days)
} else if (year === 1918) {
var days = [31, 15, 31, 30, 31, 30, 31, 31];
calculate(days)
}

function calculate(days) {
var daysOfSep = 256 - days.reduce(function(accumulator, currentValue) {
return accumulator + currentValue
}, 0)

return `${daysOfSep}.09.${year}`
}
}

console.log(solve(1918))

最佳答案

因为您没有在主函数中返回,所以默认情况下函数表达式返回未定义:

function solve(year){
if(year < 1700 || year > 2700) {
return false;
}else if(year >= 1700 && year <= 1917) {
if(year%4 === 0) {
var days = [31,29,31,30,31,30,31,31];
calculate(days)`enter code here`
}
var days = [31,28,31,30,31,30,31,31];
calculate(days)
}else if(year > 1918 && year <= 2700) {
if(year % 400 === 0 || (year%4 === 0 && year%100 !== 0)) {
var days = [31,29,31,30,31,30,31,31];
calculate(days)
}
var days = [31,28,31,30,31,30,31,31];
return calculate(days) //calculate inner function returns the result, but you do not return this.
}else if(year === 1918) {
var days = [31,15,31,30,31,30,31,31];
return calculate(days) //calculate inner function returns the result, but you do not return this.
}

function calculate (days) {
var daysOfSep = 256 - days.reduce(function(accumulator, currentValue) {
return accumulator + currentValue
},0)

return `${daysOfSep}.09.${year}`
}
}

console.log(solve(1918))
26.09.1918

关于javascript - 理解 javascript return 语句为什么返回 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50141199/

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