美文网首页es6新特性
ES6新特性与重点知识总结

ES6新特性与重点知识总结

作者: 夏海峰 | 来源:发表于2019-11-08 19:31 被阅读0次

    一、ES6变量声明

    • var 声明的变量,没有“块级作用域”的限制;
    • let / const 声明的变量,具有“块级作用域”。
    {
        var a = 1;
        let b = 2;
        const c = 3;
        let fn = function() {
            console.log(4)
        }
    }
    
    console.log(a);   // 1
    console.log(b);   // 报错ReferenceError,undefined
    console.log(c);   // 报错ReferenceError,undefined
    fn();       // ReferenceError: fn is not defined
    
    • var 声明的变量存在“变量提升”,let / const没有。
    var tmp = new Date();
    
    function fn() {
        console.log(tmp);
        if (false) {
            // var tmp 变量提升
            var tmp = 'hello world';
        }
    }
    fn()
    
    • const 声明的是常量,不能被修改。
    const c = 1;
    c = 2;      // TypeError报错
    

    二、解构赋值

    ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构。

    • 数组解构赋值
    let arr = [1, 'hello', [100,200], {a:1, b:2}, true, undefined];
    
    let [a, b, c, d, e, f] = arr
    
    console.log(a,b,c,d,e,f)
    
    • 使用解构赋值,交换两个变量的值
    let x = 1, y = 2;
    [x, y] = [y, x]
    console.log(x, y)
    
    • 对象解构赋值
    let obj = {
        a: 1,
        b: [1,2,3],
        c: false,
        d: {name: 'geekxia', age: 10 }
    }
    
    let { a, b, c, d, e } = obj
    console.log(a, b, c, d, e)
    
    // 别名
    let { b: bb } = obj
    console.log(bb)
    

    三、字符串方法扩展

    let str = 'hello world, my name is geekxia.';
    
    // 获取指定索引处理字符
    console.log(str.charAt(0))
    
    // 查询字符串中是否包含指定片段,如果存在返回索引号,如果不存在返回-1
    console.log(str.indexOf('name0'))
    
    // 判断字符串是否包含指定片段,返回布尔值
    console.log(str.includes('geekxia'))
    
    // 判断字段串是否以指定片段开头,返回布尔值
    console.log(str.startsWith('he'))
    // 判断字段串是否以指定片段结尾,返回布尔值
    console.log(str.endsWith('he'))
    
    // 对字符串重复n次,返回新的字符串
    console.log(str.repeat(2))
    
    // 对字符串进行头部补全,返回新的字符串
    console.log(str.padStart(100, '01'))
    // 对字符串进行尾部补全,返回新的字符串
    console.log(str.padEnd(100, '01'))
    

    四、Math方法扩展

    ES6 在 Math 对象上新增了 17 个与数学相关的方法。

    // 去除小数点部分
    console.log(Math.trunc(5.5))
    
    // 判断指定值是正数(1),负数(-1),还是零(0)
    console.log(Math.sign(0))
    
    // 计算立方根
    console.log(Math.cbrt(-8))
    
    // 计算两个数的平方和的平方根
    console.log(Math.hypot(3, 4))
    
    // 指数运算符
    console.log(2**4)
    

    五、函数扩展

    • 函数与解构赋值结合使用
    function add ({ a = 0, b = 0 }) {
        console.log(a + b)
    }
    add({a:2, b:3})  // 5
    add({a:2})  // 2
    add({})     // 0
    add()   // 报错
    
    • 函数的 rest 参数
    function sum(...values) {
        let total = 0;
        for (let value of values) {
            total += value
        }
        console.log(total)
    }
    sum(1,2,3)
    // 允许尾逗号
    sum(1,2,3,4,5,)
    

    六、箭头函数

    let f1 = v => v;
    let f2 = () => 5;
    let f3 = (a, b) => a + b;
    
    console.log(f1(1))
    console.log(f2())
    console.log(f3(1,2))
    
    • 由于大括号被解释为代码块,所以如果箭头函数直接返回一个对象,必须在对象外面加上括号。
    // 返回一个对象,对象要用()包裹
    let f4 = (a, b) => ({a, b})
    console.log(f4(1,2))
    

    七、扩展运算符

    扩展运算符(spread)是三个点(...)。它好比 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列。

    • 数组的操作、合并
    let arr1 = [1, 2, 3];
    let arr2 = [4, 5, 6];
    
    let arr = [...arr1, ...arr2, 7, 8, 9, 10];
    console.log(arr)
    
    • 与解构赋值配合,实现数组的截取
    let arr = [1, 2, 3, 4, 5, 6]
    
    let [a, b, ...arr1] = arr
    console.log(arr1)
    
    • 对象的操作、合并:
    let obj1 = { a:1, b:2 }
    let obj2 = { c:3, d:4 }
    
    let obj = { ...obj1, ...obj2, e:5, a:6 }
    console.log(obj)
    
    • 与解构赋值配合,操作对象:
    let obj = { a:1, b:2, c:3, d:4, e:5 }
    let { a, b, ...obj1 } = obj
    console.log(obj1)
    

    八、Array扩展

    • 把类数组转化成真正的数组:
    let arrayLike = {
        '0': 'a',
        '1': 'b',
        '2': 'c',
        length: 3
    }
    
    var arr = Array.from(arrayLike);   
    console.log(arr)  // ['a', 'b', 'c']
    
    • 把一组值,转换为数组。Array.of总是返回参数值组成的数组。如果没有参数,就返回一个空数组。
    let a = Array.of(1,2);  // [1, 2]
    let b = Array.of();     // []
    let c = Array.of(undefined);  // [undefined]
    
    console.log(a)
    console.log(b)
    console.log(c)
    
    • 数组实例的find方法,用于找出第一个符合条件的数组成员。它的参数是一个回调函数,所有数组成员依次执行该回调函数,直到找出第一个返回值为true的成员,然后返回该成员。如果没有符合条件的成员,则返回undefined。
    let res1 = [1,2,-5,10].find((ele,index,arr) => ele < 0);
    console.log(res1)
    
    • 数组实例的findIndex方法的用法与find方法非常类似,返回第一个符合条件的数组成员的位置,如果所有成员都不符合条件,则返回-1。
    let res2 = [1,5,10,15].findIndex((ele,index,arr) => ele > 9);
    console.log(res2)
    
    • 数组填充
    let res3 = new Array(4).fill(7);
    console.log(res3)
    
    • 判断指定数组中是否包含某个值
    let arr = [1, 2, 3]
    console.log([1,2,3].includes(2))
    console.log([1,2,3].includes(0,1))  // 第二参数表示索引号
    

    九、json扩展

    ES6 允许直接写入变量和函数,作为对象的属性和方法。这样的书写更加简洁。

    let foo = 'geekxia'
    function fn1() {
        console.log(1)
    }
    const obj = {
        foo,
        bar: 'hello',
        fn1,
        fn2() {
            console.log(2)
        },
        fn3: function() {
            console.log(3)
        }
    }
    
    obj.fn1()
    obj.fn2()
    obj.fn3()
    

    十、Symbol类型

    ES6 引入了一种新的原始数据类型Symbol,表示独一无二的值。它是 JavaScript 语言的第七种数据类型,前六种是:undefined、null、布尔值(Boolean)、字符串(String)、数值(Number)、对象(Object)。

    十一、Set结构

    ES6 提供了新的数据结构 Set。它类似于数组,但是成员的值都是唯一的,没有重复的值。Set 本身是一个构造函数,用来生成 Set 数据结构。

    • 使用Set结构,实现数组去重
    let arr1 = [1,2,2,2,3,4]
    let arr2 = [...new Set(arr1)]
    console.log(arr2)
    

    十二、Map结构

    ES6 提供了 Map 数据结构。它类似于对象,也是键值对的集合,但是“键”的范围不限于字符串,各种类型的值(包括对象)都可以当作键。也就是说,Object 结构提供了“字符串—值”的对应,Map 结构提供了“值—值”的对应,是一种更完善的 Hash 结构实现。如果你需要“键值对”的数据结构,Map 比 Object 更合适。

    const map = new Map();
    
    map.set({ p: 'hello world'}, 1)
    map.set('hello', [1,2,3])
    
    console.log(map.size)
    

    十三、Promise

    Promise 是异步编程的一种解决方案,比传统的解决方案——回调函数和事件——更合理和更强大。

    let promise = new Promise(function(resolve, reject) {
        setTimeout(()=>{
            if(false) {
                resolve('ok')
            } else {
                reject({err: -1, msg: '错误发生了'})
            }
        }, 1000)
    })
    
    promise.then(res=>{
        console.log(res)
    }).catch(err=>{
        console.log(err)
    }).finally(()=>{
        console.log('总会执行')
    })
    

    十四、循环遍历

    • ES6 借鉴 C++、Java、C# 和 Python 语言,引入了for...of循环,作为遍历所有数据结构的统一方法。
    • for...of循环可以使用的范围包括数组、Set 和 Map 结构、某些类似数组的对象(比如arguments对象、DOM NodeList 对象)、Generator对象,以及字符串。
    • for...of 可以与 break / continue / return 配合使用。
    let arr = [1, 2, 3, 4, 5]
    for(let ele of arr) {
        if (ele > 2) {
            break
        }
        console.log(ele)
    }
    
    • 对于普通的对象,for...of结构不能直接使用,会报错。使用 for...in 来遍历普通对象。
    let obj = {
        a: 1,
        b: 2,
        c: 3
    }
    for(let k in obj) {
        console.log(obj[k])
    }
    

    十五、async / await

    function add(a,b) {
    // 返回一个promise对象
        return new Promise((resolve, reject)=>{
            setTimeout(()=>{
                resolve(a+b)
            }, 2000)
        })
    }
    
    // await is only valid in async function
    // await 只在 async函数中有效
    async function testAdd() {
        let num = await add(2,3)
        console.log(num)
    }
    
    testAdd()
    

    十六、class类与继承

    class Point {};
    
    class ColorPoint extends Point {
        constructor(x, y, color) {
            super(x, y);   // 调用父类的 constructor(x, y)
            this.color = color;
        }
        toString() {
            return this.color + ' ' + super.toString();  // 调用父类的toString()方法
        }
    }
    

    十七、ES6模块化

    • 使用export default抛出模块
    export default xxx;   // 抛出模块
    
    import xxx from './xxx'   // 引入模块
    
    • 使用 export 抛出模块
    export const a = 1;
    export function foo() {}   // 抛出
    
    import { a, foo } from './xxx'   // 引入
    

    十八、装饰器

    许多面向对象的语言都有修饰器(Decorator)函数,用来修改类的行为。

    • 装饰器用于修饰一个类:
    @decorator
    class A {};
    
    • 装饰器用于修饰一个类的方法:
    class Person {
        @readonly
        name() { return `${this.name}` }
    }
    

    资源笔记推荐:

    本篇结束 2019年11月08日

    相关文章

      网友评论

        本文标题:ES6新特性与重点知识总结

        本文链接:https://www.haomeiwen.com/subject/kkvwbctx.html