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

js的函数参数与返回值与模板字面量与模板函数

新手1314
新手1314原创
2022年04月01日 15:03:36438浏览

函数参数

1.参数不足时,设置默认参数(代码均为script里)

  1. let a = (a,b=0) =>a+b;
  2. console.log(a(8));
  3. 输出结果为:8.若不设置默认参数b=0,则结果为NaN

2.参数过多时,使用…归并剩余参数

  1. let a =(a,b,...c) =>console.log(a,b,c);
  2. console.log(a(1,2,3,4,5,6,7,8,9,10));
  3. 输出结果为:1 2 (8) [3, 4, 5, 6, 7, 8, 9, 10]

2.1 将…用于参数调用时,作用为解包,打散

  1. let arr = [1, 2, 3, 4];
  2. console.log(...arr);
  3. 输出结果为:1 2 3 4.

函数返回值:函数只能有一个返回值,默认单值返回(如需返回多值需用数组与对象)

1.单值返回

  1. let fn = () =>[1,2,3,4];
  2. console.log(fn());
  3. 输出结果为:(4) [1, 2, 3, 4]。

2.多值返回

  1. let fn = () =>({
  2. id:1,
  3. user:"新手1314",
  4. age:20,
  5. })
  6. console.log(fn());
  7. 输出结果为:{id: 1, user: '新手1314', age: 20}

模板字面量:反引号,支持在字符串插入变量/表达式。

  1. 引号:let name = "新手1314”;
  2. console.log("hello " + name); 输出结果为:hello 新手1314
  3. 反引号:let name = "新手1314";
  4. console.log(`hello ${name}`); 输出结果为:hello 新手1314

模板函数:使用模板字面量为参数的参数

  1. user`id: ${1} user: ${"新手1314"}`;
  2. function user(strings, ...args){
  3. console.log(strings);
  4. console.log(args);
  5. console.log("id: " + args[0] + ",名字: " + args[1]);
  6. }
  7. 输出分别为:(3) ['id: ', ' user: ', '', raw: Array(3)]
  8. (2) [1, '新手1314']
  9. id: 1,名字:新手1314
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议