格式
function 函数名称(形参列表){
被封装的代码;
}
形式参数 实际参数
罗列在function小括号中的参数,叫做形式参数;调用时传递的数值,叫做实际参数
function 函数名称(形参列表){
被封装的代码;
}
函数名称(实际列表); // 函数调用
使用函数的好处
- 冗余代码少
- 需求变更时, 需要修改的代码少
函数定义步骤
- 书写函数的固定格式
- 给函数起一个有意义的名称
- 为了提升代码的阅读性
- 函数名称也是标识符的一种, 所以也需要遵守标识符的命名规则和规范
- 确定函数的形参列表
- 看看使用函数的时候是否需要传入一些辅助的数据
- 将需要封装的代码拷贝到{}中
- 确定函数的返回值
- 可以通过return 数据; 的格式, 将函数中的计算结果返回给函数的调用者
function getSum(a, b){ // a = num1, b = num2;
let res = a + b; // let res = 10 + 20; let res = 30;
// 将res返回给函数的调用者
return res;
}
let num1 = 10;
let num2 = 20;
let result = getSum(num1, num2); // let result = res; let result = 30;
console.log(result); // 30
注意点
- 一个函数可以有形参也可以没有形参(零个或多个)
// 没有形参的函数
function say() {
console.log("hello world");
}
say(); // hello world
// 有形参的函数
function say(name) {
console.log("hello " + name);
}
say("张三"); // hello 张三
- 一个函数可以有返回值也可以没有返回值
// 有返回值
function say() {
console.log("hello world");
}
say();
// 没有返回值
function getSum(a, b) {
return a + b;
}
let res = getSum(10 , 20);
console.log(res);
- 函数没有通过return明确返回值, 默认返回undefined
function say() {
console.log("hello world");
return; // undefined
}
let res = say();
console.log(res); // undefined
- return的作用和break相似, 所以return后面不能编写任何语句(永远执行不到)
- break作用立即结束switch语句或者循环语句
- return作用立即结束当前所在函数
function say() {
console.log("hello world");
return;
console.log("return后面的代码"); // 永远执行不到
}
say();
- 调用函数时实参的个数和形参的个数可以不相同
function getSum(a, b) {
return a + b;
}
let res = getSum(10, 20, 30);
console.log(res); // 30
- JavaScript中的函数和数组一样, 都是引用数据类型(对象类型)
- 既然是一种数据类型, 所以也可以保存到一个变量中
- 将一个函数保存到一个变量中 , 将来可以通过变量名称找到函数并执行函数
let say = function () {
console.log("hello world");
}
say(); // hello world