es6常用特性

默认值参数

  1. 参数在函数内不能用 letconst 再次声明

    function test(x = 5) {
      let x = 1 // 报错
      const x = 2 // 报错
    }
  2. 使用参数默认值时,函数不能有同名参数

    // 报错 Duplicate parameter name
    function test(x, x, y = 1) {
      ...
    }
  3. 入参为 undefined 或不传值会使用函数默认值;入参未''或 null 会使用传入的参数值

    function test(num = 1) {
      console.log((typeof num) + ', num的值为: ' + num)
    }
    test() // number, num的值为: 1
    test(undefined) // number, num的值为: 1
    test('') // string, num的值为: 
    test(null) // object, num的值为: null
  4. 位置在前的默认参数可用于后面的默认参数

    function test(name, height, msg = name + ' height is ' + height) {
      return [name, height, msg]
    }
    test('MuYi086', 'nihao') // ["MuYi086", "nihao", "MuYi086 height is nihao"]
    test('MuYi086', 'nihao', 'hello world') // ["MuYi086", "nihao", "hello world"]
  5. 默认值参数应当放在函数末尾,否则函数调用入参不能省略,会报错

    function test(x, y = 5, z) {
      return [x, y, z]
    }
    test(1, , 2) // 报错
  6. 有默认值,函数的 length 属性将返回没有指定默认值的参数个数.如果默认参数不是尾部参数,那么 length 属性也不在计入后面的参数.

    (function (a) {}).length // 1
    (function (a = 5) {}).length // 0
    (function (a, b = 1, c) {}).length // 1

变量声明: let和const

let 声明变量, const 声明常量,俩者都为块级作用域,仅在最近的一个块中有效

const 声明的对象内所包含的值是可以被修改的,即对象指向的地址不变.

模板字符串

ES6 以前,字符串模板常用+号进行字符串拼接

ES6 里使用反引号(`)表示普通字符串,同时可以插入变量

标签模板字面量

把目标字符串中的数值格式化为美元,示例如下:

箭头函数

扩展运算符

rest

rest 参数和一个变量名搭配使用,生成一个数组

for of

ES5 中我们常用 for in 或者 forEach 遍历,但是在最新的 ES6 ,引入了新的 for of ,用来遍历属性值 区别如下:

解构

::: code-group

:::

super

::: details 点我查看代码

:::

Promise

专门有总结过一篇关于 Promise 的使用 Promise介绍和使用

Generator Function

::: details 点我查看代码

:::

class

::: details 点我查看代码

:::

export 和 import

::: details 点我查看代码

:::

参考

Last updated

Was this helpful?