- Objective:如何在函数中添加条件语句。变量,数据类型,条件,函数 - Breadcrumb: JS I # 概念阐释 # 实例 # 相关内容 # 问题 **写出解题思路:** 🌟 - 获取当下年份 ```js function getCurrentYear() { const date = new Date(); return date.getFullYear(); } console.log(getCurrentYear()); ``` - 将负数改为正数 ```js function makePositive(num) { return Math.abs(num); } console.log(makePositive(-5)); // 输出: 5 ``` - [练习题](https://www.codecademy.com/journeys/full-stack-engineer/paths/fscj-22-building-interactive-websites/tracks/fscj-22-javascript-syntax-part-i/modules/fscj-22-practice-javascript-syntax-variables-data-types-conditionals-functions/lessons/javascript-fundamentals-code-challenge/exercises/how-old) 编写一个名为 howOld() 的函数,它有两个数字参数:年龄和年份,并返回在该年龄的人在那一年的年龄是多少(或将是多少)。处理三种不同的情况: 如果年份在未来,应返回以下格式的字符串: 1. 填写年份大于当下年份=未来 ``You will be ${diff} in the year ${year}`` 2. 如果填写年份小于出生年份=过去`The year ${year} was ${diff} years before you were born` 3. 如果填写年份在出生后和当前年份之间`You were ${diff} in the year ${year}` # 问题答案 ```js // Write your function here: let howOld = (age,year) => { //总是知道当前年份 let date = new Date(); let currentYear = date.getFullYear(); const bornYear= currentYear - age; // 计算年龄(包括未出生的负数) let diff = Math.abs(year - bornYear); //满足条件,如果填写年份大于当下年份=未来; //如果填写年份小于出生年份=过去; //中间段 if(year > currentYear){ return `You will be ${diff} in the year ${year}` }else if (year < bornYear){ return `The year ${year} was ${diff} years before you were born` }else { return `You were ${diff} in the year ${year}` }; }; // Once your function is written, write function calls to test your code! console.log(howOld(35,1986)); console.log(howOld(35,2025)); console.log(howOld(35,1993)); ``` # 参考资料 - [GPT-获取当前年份](https://chat.openai.com/share/1d1db6d9-de8f-4059-9aca-01cd20ed7fbf): 内置对象参考