模板函数
使用模板字面量为参数的函数
模板函数,有的书也翻译为”标签函数”
// 模板函数的参数:
// 第一个参数: 模板字面量中的"字符串字面量"
// 第二个参数: 模板字面量中的"插值"数组
function calc(strings, ...args) {
console.log(strings);
console.log(args);
console.log(args[0] * args[1]);
}
//调用
calc`数量: ${10}单价: ${500}`;
// Array(3) [ "数量", "单价", "" ]
// Array [ 10, 500 ]
// 5000
正常的参数
let f = (a, b) => a + b;
console.log(f(10, 20)); // 30
参数不足: 默认参数
console.log(f(10)); //NaN:not a number
f = (a, b = 2) => a + b;
console.log(f(10)); //12
参数过多: …剩余参数
f = (a, b, ...c) => console.log(a, b, c) ;
// ...rest:用在函数的参数中,归并
console.log(f(2, 3, 4, 5, 6, 7));
//2 3 Array(4) [ 4, 5, 6, 7 ]
let arr2 = [1, 2, 3, 4, 5];
console.log(f(...arr2));
//与下面的语句功能一样
console.log(f(1, 2, 3, 4, 5));
//...用在参数调用时,是解包:打散
//下面函数功能:数组中的元素累加求和
f = (...arr2) => arr2.reduce((p,c) => p + c);
console.log(f(...arr2));//15
函数返回值:只能有一个返回值
需要返回多个值时:数组或对象
本质 仍然返回一个值返回数组
let fn = () => [1, 2, 3];
let res = fn();
console.log(res);//Array(3) [ 1, 2, 3 ]
返回对象
let fn3 = () => ({
id: 2,
name: "admin",
age: 28,
});
let res3 = fn3();
console.log(res3);
// Object { id: 2, name: "admin", age: 28 }