爲何須要用到函數:
提升開發效率
複用 減小代碼量
開發維護 更靈活 把功能分開書寫
參數 返回值 讓函數更靈活編程
功能
參數
返回值數組
表達式:let fn = function () { }
聲明式: function fn() { } 會形成函數提高
構造函數:let fn = new Function(){ } 首字母大寫異步
函數名();異步編程
匿名函數:
function(){ }函數
IIFE:當即執行函數:
例:(function () { console.log(666); }()) //666this
只跟書寫方式有關,有無名字均可以用IIFE
參數:
形參
實參rest
例:let 送外賣 = function(食物){ console.log(`吃${食物}`) //形參 } 送外賣(「冒菜」) //實參 若是有形參沒實參會打印undefined、有實參沒形參則不會調用
經過return.....函數不能寫在return以後code
`例:let fn = function () { let number = 5; return number; //把值傳出去 } let a = fn(); console.log(a) //5 return 5;`
( 僞類數組對象 統計實參個數 )對象
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:
例: let arr = tunction(name = "1"){ console.log(${ name }) //1 } fn("2"); fn();
例: 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);
例: let fn = function ([a, b]) { //a=1 b=2 console.log(a, b) //1,2 } fn([1, 2]);
例:
1. let fn = function (x, y) { ......... } fn();
將函數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