Blogger Information
Blog 12
fans 0
comment 0
visits 9409
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
实例演示函数参数与返回值、实例演示模板字面量与模板函数
P粉355147598
Original
467 people have browsed it

实例演示函数参数与返回值

1、函数的形参数量与实参数量对应

  1. let fn = (a , b) => a + b;
  2. console.log(fn(1 , 2));

2、函数的形参数量与实参数量不对应

(1)实参少于形参

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

使用默认参数

  1. //默认参数=0
  2. let fn = (a , b=0) => a + b;
  3. console.log(fn(1));
  4. console.log(fn(1,2));

  1. //默认参数不为0
  2. let fn = (a , b=1) =>a + b;
  3. console.log(1);

(2)实参多于形参

  1. let fn = (a , b) => a + b;
  2. console.log(fn(1,2,3,4,));

无法接受到全部的参数,这里我们需要用剩余参数’…‘

1)剩余参数的使用方法一

  1. let fn = (a , b , ...c) => console.log(a,b,c);
  2. fn(1,2,3,4,5);
  3. //这里最终是将多出来的参数都压入到数组c中去了

2)剩余参数用在参数调用时的实参中就是解包、打散

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

3)通过剩余参数接收全部参数

  1. fn = (...arr) => arr.reduce((a,c)=>a + c);
  2. console.log(1,2,3,4,5,6,7,8,9);

3、函数返回值

函数只能有一个返回值,默认单值返回,那么我们需要返回多个值怎么办?我们可以利用数组和对象,但是本质上任然返回的是一个值,只不过这是一个引用类型的复合值。

  1. let fn = () => [1 , 2 , 3];
  2. let arr = fn();
  3. console.log(arr);
  4. let fn1 = () =>(
  5. {
  6. id:2,
  7. name:'admin',
  8. age:25,
  9. }
  10. );
  11. let result = fn1();
  12. console.log(result);

实例演示模板字面量与模板函数

1、模板字面量

  1. //反引号:模板字面量,支持在字符串插入变量、表达式
  2. let name = '张三';
  3. console.log(`Hello ${name}`);

  1. let gender = 1;
  2. console.log(`${gender?`男:${name}`:'女'}`);

2、模板函数

  1. // 模板函数的参数:
  2. // 第一个参数: 模板字面量中的"字符串字面晨"
  3. // 第二个参数: 模板字面量中的"插值"数组
  4. calc`数量: ${10}单价: ${500}`;
  5. function calc(strings, ...args) {
  6. console.log(strings);
  7. console.log(args);
  8. console.log(args[0] * args[1]);
  9. }

Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post