zoukankan      html  css  js  c++  java
  • es6-7 函数扩展

    函数的默认参数

    {
        function test (x, y='world') {
            console.log('默认值', x, y)
        }
        test('hello'); // hello world
        test('hello', 'day') // hello day
    }

    注意块作用域的优先级

    {
        let x = 'test'
        function test2 (x, y=x) {
            console.log('默认值', x, y)
        }
        test2('hello'); // hello hello
    }
    
    {
        let c = 'test'
        function test2 (x, y=c) {
            console.log('默认值', x, y)
        }
        test2('hello'); // hello test
    }

    rest 参数 ...arg

    不知道会有多少参数这种方式会把传入的参数转化成一个数组

    PS: rest 参数后不能再有其他参数

    {
        function test3(...arg) {
            for (let v of arg) {
                console.log('rest', v); // '1', 2, 3, '4'
            }
        }
        test3('1', 2, 3, '4')
    }

    扩展运算符

    把数组拆分成离散的值
    {
        console.log(...[1,2,3]); // 1 2 3
        console.log('a', ...[1,2,3]); // 'a' 1 2 3
    }

    箭头函数

    箭头函数由 函数名 参数 返回值 三部分组成, 没有参数用 () 代替, 注意箭头函数 this 指向创建时候的 this, 而不是调用时的 this, 根据业务场景考虑是否需要使用箭头函数

    {
        let arrow = v => v * 2; // 函数名 参数 返回值 [没有参数用 () 表示]
        console.log(arrow(3)); // 6
        
        let arrow2 = () => 5
        console.log(arrow2()); // 5
    }

    尾调用

    尾调用可以提升性能, 之前用递归是一个函数地址嵌套是相当耗费资源的

    {
        function tail(x) {
            console.log('tail', x); // 123
        }
        function fx(x) {
            return tail(x)
        }
        fx(123)
    }
  • 相关阅读:
    mina 字节数组编解码器的写法 I
    latex编写论文
    HTML学习
    Apache Mina Filter
    静态循环队列的相关操作及详解
    hdu1242 Rescue(BFS +优先队列 or BFS )
    让我们区分质量保证与测试
    新玩的windows phone app studio
    Pylons安装苦逼之路
    [置顶] js 实现 <input type="file" /> 文件上传
  • 原文地址:https://www.cnblogs.com/helzeo/p/11813412.html
Copyright © 2011-2022 走看看