ES6

ES6特性第二部分

2019-09-26  本文已影响0人  Aniugel
知识点
数组:
    ES5里面新增一些东西

    循环:
        1. for
            for(let i=0; i<arr.length; i++)
        2. while

    arr.forEach()  //  代替普通for
        arr.forEach(function(val, index, arr){
            console.log(val, index, arr);
        });
    arr.map()  //  非常有用,做数据交互  "映射"
        正常情况下,需要配合return,返回是一个新的数组
        若是没有return,相当于forEach

        注意:平时只要用map,一定是要有return
        
        重新整理数据结构:
            [{title:'aaa'}]   ->  [{t:'aaaa'}]

    arr.filter():  过滤,过滤一些不合格“元素”, 如果回调函数返回true,就留下来
        
    arr.some(): 类似查找,  数组里面某一个元素符合条件,返回true
    arr.every(): 数组里面所有的元素都要符合条件,才返回true

    其实他们可以接收两个参数:
        arr.forEach/map...(循环回调函数, this指向谁);
    ------------------------------------------------------------
    arr.reduce()   //从左往右
        求数组的和、阶乘
        
    arr.reduceRight()  //从右往左
    ------------------------------------------------------------    

ES2017新增一个运算符:
    幂
        Math.pow(2,3)
        2 ** 3
======================================================
for....of....:
    arr.keys()  数组下标
    arr.entries()   数组某一项

    for(let val of arr){
        console.log(val);
    }
======================================================
扩展运算符:
    ...

    let arr =[1,2,3];
    let arr2 = [...arr];

    let arr2 = Array.from(arr);

Array.from:
    作用: 把类数组(获取一组元素、arguments...) 对象转成数组

    个人观点: 具备 length这个东西,就靠谱

Array.of():  把一组值,转成数组
    let arr = Array.of('apple','banana','orange');

    console.log(arr);

arr.find():  查找,找出第一个符合条件的数组成员,如果没有找到,返回undefined

arr.findIndex(): 找的是位置, 没找到返回-1


arr.fill()  填充
    arr.fill(填充的东西, 开始位置, 结束位置);

在ES2016里面新增:

    arr.indexOf()
    arr.includes()
        str.includes()
============================================
对象:
    json

    对象简介语法(相当有用):

    let json ={
        a:1,
        b:2,
        showA:function(){
            return this.a;
        }
        showB:function(){
            return this.b;
        }
    }

    let json ={
        a,
        b,
        showA(){  //个人建议: 一定注意,不要用箭头函数
        },
        showB(){
        }
    }


    new Vuex.Store({
        state,
        mutation,
        types,
        actions
    });

    new Vue({
        router,
        App,
        vuex
    })

Object.is():    用来比较两个值是否相等

    Object.is('a','a');

    比较两个东西相等:
        ==
        ===

    Object.is(NaN, NaN);

    Object.is(+0, -0);

Object.assign():   用来合并对象
    let 新的对象 = Object.assign(目标对象, source1, srouce2....)

    function ajax(options){  //用户传
        let defaults={
            type:'get',
            header:
            data:{}
            ....
        };

        let json = Object.assign({}, defaults, options);
        .....
    }
    

    用途:
        1. 复制一个对象
        2. 合并参数

ES2017引入:
    Object.keys()
    Object.entries();
    Object.values();

        let {keys, values, entries} = Object;let {keys, values, entries} = Object;

    let json = { a: 3, b: 4 };
    let json2 = { ...json };
    console.log(json2 === json)//false
    console.log(Object.assign({}, json) === json)//false
    console.log(Object.assign(json) === json)//true

==================================================
Promise:    承诺,许诺

    作用:  解决异步回调问题

    传统方式,大部分用回调函数,事件

    ajax(url,{  //获取token
        ajax(url,()=>{  //获取用户信息
            ajax(url, ()=>{
                //获取用户相关新闻
            })
        })
    })

    语法:
        let promise = new Promise(function(resolve, reject){
            //resolve,   成功调用
            //reject     失败调用
        });

        promise.then(res=>{

        }, err=>{
            
        })


    promise.catch(err=>{})

    本人用法:
        new Promise().then(res=>{

        }).catch(err=>{
            
        })

    Promise.resolve('aa') :  将现有的东西,转成一个promise对象, resolve状态,成功状态
        等价于:
        new Promise(resolve =>{
            resolve('aaa')
        });
    Promise.reject('aaa'):   将现有的东西,转成一个promise对象,reject状态,失败状态
        等价于:
        new Promise((resolve, reject) =>{
            reject('aaa')
        });

√   Promise.all([p1, p2, p3]):  把promise打包,扔到一个数组里面,打包完还是一个promise对象
        必须确保,所有的promise对象,都是resolve状态,都是成功状态
    Promise.race([p1, p2, p3]): 只要有一个成功,就返回

    用户登录  ->  用户信息
=========================================
模块化:
    js不支持模块化
        ruby   require
        python  import
    
    在ES6之前,社区制定一套模块规范:
        Commonjs        主要服务端  nodeJs    require('http')
        AMD         requireJs, curlJs
        CMD         seaJs

    ES6出来,同意服务端和客户端模块规范:
        import {xx} ddd
        
        Math.pow()
        Math.abs()

        import {pow, abs} from 'Math'       我自己瞎想


    模块化:
        注意: 需要放到服务器环境
        a). 如何定义模块?
            export  东西
            export const a =12;
            export{
                a as aaa,
                b as banana
            }
        b). 如何使用?
            import
            import './modules/1.js'; 
            import {a as a, banana, c} from './modules/2.js'
            import * as modTwo from './modules/2.js';
    使用模块:
        <script type="module"></script>


    import:  特点
        a). import 可以是相对路径,也可以是绝对路径
            import 'https://code.jquery.com/jquery-3.3.1.js';
        b). import模块只会导入一次,无论你引入多少次
        c). import './modules/1.js';  如果这么用,相当于引入文件
        d). 有提升效果,import会自动提升到顶部,首先执行
        e). 导出去模块内容,如果里面有定时器更改,外面也会改动,不想Common规范缓存


    * import()  类似node里面require, 可以动态引入, 默认import语法不能写到if之类里面
        返回值,是个promise对象

        import('./modules/1.js').then(res=>{
            console.log(res.a+res.b);
        });

        优点:
            1. 按需加载
            2. 可以写if中
            3. 路径也可以动态

        Promise.all([])
    =============================================
    ES2017加  async  await:
=============================================
'use strict'        以后默认就是严格模式
<body>
    <ul>
        <li>888</li>
        <li>888</li>
        <li>888</li>
        <li>888</li>
    </ul>
    <script>
        // ES2017新增一个运算符:幂

        // console.log(Math.pow(2, 3))
        // console.log(2 ** 3)

        // for of

        // let arr = [2, 3, 21]
        // for (let val of arr.keys()) {
        //     console.log(val)//0 1 2
        // }
        // for (let val of arr.entries()) {
        //     console.log(val)//每一项
        // }
        // for (let [index, value] of arr.entries()) {
        //     console.log(index, value)//每一项
        // }

        // 扩展运算符

        // let arr = [1, 2, 3];
        // let arr2 = [...arr];//复制一个数组 方法一
        // let arr2 = Array.from(arr);//复制一个数组 方法二

        // Array.from: 作用: 把类数组(获取一组元素、arguments...) 对象转成数组  具有length属性

        // let liNode = document.getElementsByTagName('li')
        // console.log(liNode)//HTMLCollection(4) [li, li, li, li] 类数组
        // // liNode.pop()//报错  不具有数组的方法
        // console.log([...liNode])//转换成数组 [li, li, li, li]
        // console.log(Array.from(liNode))//转换成数组 [li, li, li, li]
        // console.log(Array.prototype.slice.call(liNode))//转换成数组 [li, li, li, li]
        // console.log([].slice.call(liNode))//转换成数组 [li, li, li, li]

        // let json = {
        //     0: 'apple',
        //     1: 'banana',
        //     2: 'orange',
        // }
        // console.log(Array.from(json)) //[] 不具有length属性 解析成空数组


        // let json = {
        //     0: 'apple',
        //     1: 'banana',
        //     2: 'orange',
        //     length: 2
        // }
        // //[] 具有length属性 解析成数组  长度为多少显示几个元素
        // console.log(Array.from(json))// ["apple", "banana"]



        // Array.of(): 把一组值,转成数组
        // let arr = Array.of('apple', 'banana', 'orange', 1, 2);
        // console.log(arr);

        // arr.find(): 查找,找出第一个符合条件的数组成员,如果没有找到,返回undefined

        // var arr = [2, 3, 4, 5, 100]
        // console.log(arr.find(() => x = 2))//  2 x可以不传入
        // console.log(arr.find((x) => x > 2))// 3 第一个满足条件的

        // // arr.findIndex(): 找的是位置, 没找到返回 - 1
        // console.log(arr.findIndex((x) => x = 2))// 3 第一个满足条件的

        // // arr.fill()  填充
        // // arr.fill(填充的东西, 开始位置, 结束位置);
        // console.log(arr.fill(0, 0, 4))// 3 第一个满足条件的

        // var str = 'hgjklkjh';

        // console.log(arr.indexOf())
        // console.log(arr.includes())
        // console.log(str.includes('k'))

        // 对象简介语法
        // var b = 0;
        // let json = {
        //     a: 1,
        //     b: 2,
        //     showA: function () {
        //         return this.a;
        //     },
        //     showB: () => { //用箭头函数  直接指向window 
        //         return this.b;
        //     }
        // }
        // console.log(json.showA())//1
        // console.log(json.showB())//0 

        // let a = 1;
        // let b = 2;
        // let json = {
        //     a, //a:a
        //     b, //b:b
        //     showA() {  //个人建议: 一定注意,不要用箭头函数
        //         return this.a
        //     },
        //     showB() {
        //         return this.b
        //     }
        // }
        // console.log(json.a)//1
        // console.log(json.b)//2

        // console.log(json.showA())//1
        // console.log(json.showB())//2

        // let x = 1;
        // let y = 2;

        // function fn({ x, y }) {
        //     console.log(x, y)//1 2
        // }
        // fn({ x, y })

        // Object.is() //用来比较两个值是否相等
        // console.log(Object.is('a', 'a'))//true
        // console.log(Object.is([], []))//false
        // console.log(Object.is(NaN, NaN))//true
        // console.log(Object.is(-0, +0))//false
        // console.log(-0 === +0)//true

        // Object.assign(): 用来合并对象或者合并一个参数
        // let 新的对象 = Object.assign(目标对象, source1, srouce2....)

        // let json1 = { a: 1 }
        // let json2 = { b: 2 }
        // let json3 = { c: 3 }
        // let json4 = [1, 2]
        // let obj = Object.assign({}, json1, json2, json3)
        // console.log(obj) //{a: 1, b: 2, c: 3}

        // let arr = [1, 2, 4, 5]
        // // console.log(Object.assign([], arr) === arr)
        // console.log(arr)// [1, 2, 4, 5]
        // let arr2 = Object.assign([], arr)
        // // let arr2 = Array.from(arr)
        // // let arr2 = [...arr]
        // // let arr2 = arr
        // arr2.push('9')
        // console.log(arr2)//[1, 2, 4, 5, "9"]
        // console.log(arr)// [1, 2, 4, 5]

        // let json = { a: 3, b: 4 };
        // let json2 = { ...json };
        // // let json2 = json
        // console.log(json2)// false
        // console.log(json === json2)//

        // Object.keys()
        // Object.entries();
        // Object.values();

        // var obj = { a: 1, b: 2, c: 3 }//普通对象不能用for of
        // for (val of Object.keys(obj)) {
        //     console.log(val)// a b c
        // }
        // var obj = { a: 1, b: 2, c: 3 }
        // for (val of Object.values(obj)) {
        //     console.log(val)// 1 2 3
        // }
        // var obj = { a: 1, b: 2, c: 3 }
        // for (val of Object.entries(obj)) {
        //     console.log(val)// ["a", 1] ["b", 2] ["c", 3] 
        // }
        // var obj = { a: 1, b: 2, c: 3 }
        // for (let [key, val] of Object.entries(obj)) {
        //     console.log(val, key)
        // }

        // // let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }
        // // console.log(x, y, z)//1 2 {a: 3, b: 4}

        // let json = { a: 1, b: 2 }
        // let json1 = { ...json }
        // console.log(json === json1)//false
        // delete json1.b
        // console.log(json1)//{a: 1}

        // Promise

        // let a = 10;
        // console.log('8888')
        // let promise = new Promise(function (resolve, reject) {
        //     if (a == 1) {
        //         resolve('成功')
        //         // console.log('success')

        //     } else {
        //         reject('失败')
        //         // console.log('fail')
        //     }
        // })

        // promise.then(success,fail)

        // promise.then(res => {
        //     console.log(res)//成功
        // }, err => {
        //     console.log(err)//失败
        // })

        // promise.then(res => {
        //     console.log(res)
        // })

        // promise.catch(err => {
        //     console.log(err)
        // })

        // promise.then(res => {
        //     console.log(res)
        // }).catch(err => {
        //     console.log(err)
        // })

        // let p1 = Promise.resolve('成功')
        // let p2 = Promise.reject('失败')
        // p1.then(res => {
        //     console.log(res)//成功
        // }).catch(err => {
        //     console.log(err)
        // })
        // p2.then(res => {
        //     console.log(res)
        // }).catch(err => {
        //     console.log(err)//失败
        // })

        // let p1 = Promise.resolve('aaa')
        // let p2 = Promise.resolve('bbb')
        // let p3 = Promise.resolve('ccc')
        // Promise.all([p1, p2, p3]).then(res => {
        //     let [res1, res2, res3] = res
        //     console.log(res)
        // })

        // let p1 = Promise.resolve('aaa')
        // let p2 = Promise.reject('bbb')
        // let p3 = Promise.resolve('ccc')
        // Promise.all([p1, p2, p3]).then(res => {
        //     let [res1, res2, res3] = res
        //     console.log(res)
        // }).catch(err => {
        //     console.log(err)//bbb
        // })
    </script>
</body>
上一篇 下一篇

猜你喜欢

热点阅读