ES6学习笔记<四> default、rest、Multi-line Strings

default 参数默认值

在实际开发 有时需要给一些参数默认值。

在ES6之前一般都这么处理参数默认值

    function add(val_1,val_2){
        val_1 = val_1 || 10;
        val_2 = val_2 || 20;
        return console.log(val_1 + val_2);
    }
    add();    // 30

而现在可以这么做

    function add_1(val_1 = 5,val_2 = 10){
        return console.log(val_1 + val_2);    
    }
    add_1();    // 15

rest参数

rest参数类似C#中的params参数,以数组方式接收任意数量参数。

    function fun(...arr){
        console.log(arr);
    }
    class p{
        constructor(){
            this.a = "a";
            this.b = "b";
        }
    }
    let obj_p = new p();
    fun("w","e","s","t");    // ["w", "e", "s", "t"]
    fun("life");            // ["life"]
    fun(obj_p);        // [ 'obj'(p) ]

不论参数类型是什么均已数组方式接收。rest参数用 ... 作前缀来修饰参数。

    function fun(par,...arr){
        console.log(par);
        console.log(arr);
    }
    fun("w","e","s","t");    // w , ["e", "s", "t"]

par接收第一个参数"w";arr接收剩下的所有参数且生成数组。

来看一个综合例子

    function* fun(val,...arr){
        for(let i = 0; i < arr.length; i++){
            if(arr[i] <= 5){
                yield val + arr[i];
            }else if((arr[i] + val) > 10){
                return arr[i] + val;
            }
        }
    }
    let f_1 = fun(7,9,8,7,6,5,4,3,2,1,0);
    console.log(f_1.next());    // Object {value: 16, done: true}
    console.log(f_1.next());    // Object {value: undefined, done: true}

复习之前提到的生成器函数和yield,当第一次执行生成器函数变量就执行return,那么生成器函数的done值直接为true且不在执行迭代。

Multi-line Strings 多行字符串

    var str1 = `This life is the crossing of asea,
                        where we meet in the same narrow ship.`;
    var str2 = "This life is the crossing of asea," + "where we meet in the same narrow ship.";
    console.log(str1);
    // This life is the crossing of asea,
    //                where we meet in the same narrow ship.
    console.log(str2);
    // This life is the crossing of asea,where we meet in the same narrow ship.

这个特性很易懂,ES6之前做多行字符串需要用 加号 连接,ES6 仅需用反引号即可,而且反引号中的空格缩进都有用。

ES6学习笔记目录

ES6学习笔记<一> let const class extends super

ES6学习笔记<二>arrow functions 箭头函数、template string、destructuring

ES6学习笔记<三> 生成器函数与yield

ES6学习笔记<四> default、rest、Multi-line Strings

ES6学习笔记<五> Module的操作——import、export、as

原文地址:https://www.cnblogs.com/MirageFox/p/7580908.html