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)
    }
  • 相关阅读:
    hdoj 6023 Automatic Judge
    hdoj 1170 Balloon Comes!
    初识vim操作和配置
    POJ 1611 The Suspects (并查集)
    HDU 1232 畅通工程 (并查集)
    计蒜客--两数之和
    计蒜客--爬楼梯 (动态规划)
    计蒜客--单独的数字 (位运算)
    计蒜客--最后一个单词的长度
    计蒜客-- 奇怪的国家 (位运算)
  • 原文地址:https://www.cnblogs.com/helzeo/p/11813412.html
Copyright © 2011-2022 走看看