博客列表 >函数参数与返回值 、模板字面量与模板函数的学习

函数参数与返回值 、模板字面量与模板函数的学习

阿杰
阿杰原创
2022年04月02日 16:59:32437浏览

一、函数的参数与返回值

(1) 参数不足要设置默认参数,否则出现NaN

  1. let f = (a,b) => a+b;
  2. console.log(f(10,20));
  3. console.log(f(10));

(2) 参数过多,用 … 接收剩余参数

  1. f = (a,b) => console.log(a,b);
  2. f(1,2,3,4,5);
  3. f = (a, b, ...c) => console.log(a,b,c);
  4. f(1,2,3,4,5);

(3)…用在参数调用时的实参中,是解包,打散

  1. let arr = [1,2,3,4,5];
  2. console.log(...arr);
  3. f(...arr);

(4)函数只能有一个返回值,默认单值返回

  1. let fn = () => [1, 2, 3];
  2. let res = fn();
  3. console.log(res);

(5) 函数需要返回多个值怎么办? 可以使用 引用类型 的复合值

  1. let fn2 = () => [1, 2, 3];
  2. let res2 = fn2();
  3. console.log(res2);
  4. fn3 = () => ({
  5. id: 2,
  6. name: 'admin',
  7. age: 28,
  8. });
  9. res3 = fn3();
  10. console.log(res3);

二、模板字面量与模板函数

(1)模板字面量

  • 反引号:模板字面量, 支持在字符串插入变量/表达式: 插值
  1. let name = '小明';
  2. console.log('hello ' + name);
  3. console.log(`hello ${name}`);
  4. let gender = true;
  5. console.log(`${gender ? `男:${name}`:`女`}`);

(2)模板函数

  • 可以使用”模板字面量”为参数的函数
  • 模板函数第一个参数:为模板字面量中的”字符串字面量
  • 模板函数第二个参数:模板字面量中的”插值”数组
  1. calc`数量: ${10}单价: ${500}`;
  2. function calc(strings, ...args) {
  3. console.log(strings);
  4. console.log(args);
  5. }

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议