关于javascript:javascript基础课堂三-函数

6次阅读

共计 1782 个字符,预计需要花费 5 分钟才能阅读完成。

函数

为什么须要用到函数:
进步开发效率
复用 缩小代码量
开发保护 更灵便 把性能离开书写
参数 返回值 让函数更灵便

函数三要素:

性能
参数
返回值

创立函数:

表达式:let fn = function () {}
申明式:function fn() {} 会造成函数晋升
构造函数:let fn = new Function(){} 首字母大写

调用函数:

函数名();

匿名函数:
function(){}

IIFE:立刻执行函数:
例:(function () {console.log(666); }()) //666

只跟书写形式无关,有无名字都能够用 IIFE
参数:
形参
实参

例:let 送外卖 = function(食物){console.log(` 吃 ${食物}`) // 形参
 }
 送外卖(“冒菜”)// 实参
 如果无形参没实参会打印 undefined、有实参没形参则不会调用
返回值:

通过 return….. 函数不能写在 return 之后

` 例:let fn = function () {
 let number = 5;
 return number; // 把值传出去
 }
 let a = fn();
 console.log(a) //5
 return 5;`
  1. return
  2. 无 return
  3. return 后的语句不执行
  4. return 只能返回一个值,多个值用 [] 数组

(伪类数组对象 统计实参个数)

arguments[index] 也能接管实参

arguments 是函数的属性、返回所有实参内容

能够相似于数组的应用形式进行值的获取

 例:function fn(a, b) {console.log(fn.arguments[0]); //1  获取下标为 0 所对应的实参 1
 console.log(fn.arguments); //0:1  1:2  2:3  获取全副实参
 console.log(fn.arguments.length); // 2  获取实参下标长度
 console.log(arguments[2]); //3 调用没有应用的实参
 }
 fn("1", "2", "3")
函数的执行:

函数的书写程序,不能决定函数的执行程序
ES6:

  1. 默认参数,形参 = 默认值,有实参用实参,无实参用默认参
 例:let arr = tunction(name = "1"){console.log(${ name}) //1
 }
 fn("2");
 fn();
  1. 残余参数 … 参数写在形参最初,真数组(不定参)以数组储存
例:let fn = function (x, y...rest) {console.log(x, y) //1,2
 console.log(rest) //[3.4]
 }
 fn(1, 2, 3, 4);

函数长度:

 function f70(a, b, c = 2) {console.log(f70.length); //2
 }
 f70(1, 2, 3, 4, 5, 6);
 
 function f70(a, b, ...c) {console.log(f70.length); //2
 }
 f70(1, 2, 3, 4, 5, 6);

 function f70(a = 0, b, c) {console.log(f70.length); //0
 }
 f70(1, 2, 3, 4, 5, 6);
  1. 解构
 例:let fn = function ([a, b]) { //a=1 b=2
 console.log(a, b) //1,2
 }
 fn([1, 2]);
  1. 箭头函数的简写

例:

 1. let fn = function (x, y) {.........}
 fn();
  1. let fn = (x, y) => {}
  2. let fn = x => {} 只有一个参数
  3. let fn = x => a – b 当只有一个 return
  4. 箭头函数不能利用于构造函数
  5. arguments 不能应用
  6. 不会吧本人得 this 绑定到函数上
函数回调:

将函数 A 作为参数传给函数 B,在函数 B 中调用,函数 A 就是 callback

callback 在异步编程当中用的较多,目前都是应用本人存在的 sort, som, fliter, foEach 等

 例:let fnA = function () {console.log(666); //666
 }
 let fnB = function (cb) {cb();
 }
 fnB(fnA);

递归(一个函数间接或间接的调用本人)

有限递归:
例:let fn = function () {fn();
 }
 fn();
归并:

例:

let arr = [1, 2, 3]
 let result = arr.reduce((a, b) => a * b);
 console.log(result) //6
正文完
 0