javascript基础课堂三 函数
码农天地 -函数
为什么需要用到函数:
提高开发效率
复用 减少代码量
开发维护 更灵活 把功能分开书写
参数 返回值 让函数更灵活
功能
参数
返回值
表达式: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;`
return无returnreturn后的语句不执行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:
例: 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();
let fn = (x, y) => { }let fn = x => { } 只有一个参数let fn = x => a - b 当只有一个return箭头函数不能应用于构造函数arguments不能使用不会吧自己得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
特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。
上一篇: 深入浅出FaaS的两种进程模型