函数参数
1.参数不足时,设置默认参数(代码均为script里)
let a = (a,b=0) =>a+b;
console.log(a(8));
输出结果为:8.若不设置默认参数b=0,则结果为NaN。
2.参数过多时,使用…归并剩余参数
let a =(a,b,...c) =>console.log(a,b,c);
console.log(a(1,2,3,4,5,6,7,8,9,10));
输出结果为:1 2 (8) [3, 4, 5, 6, 7, 8, 9, 10]
2.1 将…用于参数调用时,作用为解包,打散
let arr = [1, 2, 3, 4];
console.log(...arr);
输出结果为:1 2 3 4.
函数返回值:函数只能有一个返回值,默认单值返回(如需返回多值需用数组与对象)
1.单值返回
let fn = () =>[1,2,3,4];
console.log(fn());
输出结果为:(4) [1, 2, 3, 4]。
2.多值返回
let fn = () =>({
id:1,
user:"新手1314",
age:20,
})
console.log(fn());
输出结果为:{id: 1, user: '新手1314', age: 20}
模板字面量:反引号,支持在字符串插入变量/表达式。
引号:let name = "新手1314”;
console.log("hello " + name); 输出结果为:hello 新手1314
反引号:let name = "新手1314";
console.log(`hello ${name}`); 输出结果为:hello 新手1314
模板函数:使用模板字面量为参数的参数
user`id: ${1} user: ${"新手1314"}`;
function user(strings, ...args){
console.log(strings);
console.log(args);
console.log("id: " + args[0] + ",名字: " + args[1]);
}
输出分别为:(3) ['id: ', ' user: ', '', raw: Array(3)]
(2) [1, '新手1314']
id: 1,名字:新手1314