深入理解ES6读书笔记3:函数

参数默认值

未提供参数,或将参数值指定为undefined时,默认值会被使用。

function add(a, b = 2, c = 3){
    let result = a + b + c;
    console.log(result);
}
add(1); //6
add(1,2); //6
add(1,undefined,4); //7
add(1,null,4);

参数默认值表达式

参数默认值除了是基本类型的值,也可以执行一个函数来产生默认值。

function getValue(){
    return 5;
}
//未提供第二个参数时,getValue()才会被调用     
function add(a, b = getValue()){
    return a + b ;    
}
console.log(add(1,1)); //2
console.log(add(1)); //6

getValue()函数也可以返回可变的值。

let value = 5;
function getValue(){
    return value++;
}     
function add(a, b = getValue()){
    return a + b ;    
}
console.log(add(1,1)); //2
console.log(add(1)); //6
console.log(add(1)); //7

可以将前面的参数作为后面参数的默认值(反之,后面参数作为前面参数的默认值不行)

function add(a, b = a){
    return a + b ;    
}
console.log(add(1,1)); //2
console.log(add(1)); //2

也可以将前面的参数a作为参数传递给一个函数来产生参数b的值。

function getValue(value){
    return value + 5;
}
function add(a, b = getValue(a)){
    return a + b ;    
}
console.log(add(1,1)); //2
console.log(add(1)); //7

剩余参数

剩余参数由三个点(...)与一个紧跟着的具名参数指定,它会是包含传递给函数的其余参数的一个数组。
函数只能有一个剩余参数,并且它必须放在最后。

function add(a, ...last){
    let b = 0;
    for(let i=0;i<last.length;i++){
        b += last[i];
    }
    return a + b ;    
}
console.log(add(1)); //1
console.log(add(1,2)); //3
console.log(add(1,2,3)); //6

扩展运算符

剩余参数把多个独立的参数合并到一个数组中;扩展运算符则允许将一个数组分割,并将各个项作为分离的参数传给函数。

//Math.max()方法接受任意数量的参数
let a = 25,
    b = 50;    
console.log(Math.max(a,b)); //50

//ES5或更早版本
let values = [25,50,75,100];
console.log(Math.max.apply(Math, values)); //100

//扩展运算符
console.log(Math.max(...values));//100

箭头函数

没有参数

var f = () => 'Hello';
console.log(f()); //Hello

一个参数

var f = a => a * a;
console.log(f(2)); //4

多个参数

var f = (a,b) => a + b;
console.log(f(2,3)); //5

 创建立即调用函数表达式

//传统函数
let f1 = function(name){
    return {
        getName: function(){
            return name;
        }
    }
}("f1");
console.log(f1.getName()); //f1

//箭头函数
let f2 = ((name) => {
    return {
        getName: function(){
            return name;
        }
    }
})("f2");
console.log(f2.getName()); //f2
原文地址:https://www.cnblogs.com/gdjlc/p/14527156.html