这节课我们来通过我们之前学过的函数来逐渐完善!
const yearsUntilRetiremen = (birthyear, firstName) => {
const age = 2037 - birthyear;
const retirement = 65 - age;
return `${firstName}还有${retirement}年就退休了!`;
}
这个是我们之前写的代码,功能就是计算某某某还有多久就退休了,现在我们可以适用组合函数的方式把age的功能单独写出来;
const calcAge = function (birthYear) {
return 2037 - birthYear;
};
const yearsUntilRetiremen = function (birthyear, firstName) {
const age = calcAge(birthyear);
const retirement = 65 - age;
return `${firstName}还有${retirement}年就退休了!`;
};
● 然后现在我们尝试给函数传参
const calcAge = function (birthYear) {
return 2037 - birthYear;
};
const yearsUntilRetiremen = function (birthyear, firstName) {
const age = calcAge(birthyear);
const retirement = 65 - age;
return `${firstName}还有${retirement}年就退休了!`;
};
console.log(yearsUntilRetiremen(1998, "王半仙"));
● 但是如果是传一个已经退休的参数
const calcAge = function (birthYear) {
return 2037 - birthYear;
};
const yearsUntilRetiremen = function (birthyear, firstName) {
const age = calcAge(birthyear);
const retirement = 65 - age;
return `${firstName}还有${retirement}年就退休了!`;
};
console.log(yearsUntilRetiremen(1998, "王半仙"));
console.log(yearsUntilRetiremen(1930, "张三"));
● 一般情况下,我们可能只需要只要你还有多少年退休,如果退休了,就不需要展现多少年
const calcAge = function (birthYear) {
return 2037 - birthYear;
};
const yearsUntilRetiremen = function (birthyear, firstName) {
const age = calcAge(birthyear);
const retirement = 65 - age;
if (retirement > 0) {
return retirement;
console.log(`${firstName}还有${retirement}年就退休了`);
} else {
return -1;
console.log(`${firstName}已经退休了`);
}
};
console.log(yearsUntilRetiremen(1998, "王半仙"));
console.log(yearsUntilRetiremen(1930, "张三"));
为什么函数内部的console.log不输出出现呢,因为return会直接返回结果,不会执行下面的代码,所以我们要讲console.log移动上去
const calcAge = function (birthYear) {
return 2037 - birthYear;
};
const yearsUntilRetiremen = function (birthyear, firstName) {
const age = calcAge(birthyear);
const retirement = 65 - age;
if (retirement > 0) {
console.log(`${firstName}还有${retirement}年就退休了`);
return retirement;
} else {
console.log(`${firstName}已经退休了`);
return -1;
}
};
console.log(yearsUntilRetiremen(1998, "王半仙"));
console.log(yearsUntilRetiremen(1930, "张三"));
函数回顾:3种不同的函数类型
函数声明:
在声明之前可以使用的函数
函数表达式:
本质上是存储在变量中的函数值;
箭头函数:
伟大的一个快速的单行功能。已经没有这个关键字(以后更多…)
注:编写函数的三种不同方式,但它们的工作方式都很相似。接收输入数据,转换数据,然后输出数据