ES6入门到进阶(二):循环、数组、对象

发布时间:2019-08-15 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了ES6入门到进阶(二):循环、数组、对象脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

上一篇:ES6入门到进阶(一):let、解构赋值、字符串模板、函数

一、循环

ES5里面新增一些东西

1.1 arr.foreach()(常用)

    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);
    });

1.2 arr.map()(常用)

arr.map()  //  `非常有用,做数据交互`  "映射"
    正常情况下,需要配合return,返回是一个新的数组
    若是没有return,相当于forEach

    注意:平时只要用Map,一定是要有return
    
    重新整理数据结构:
        [{title:'aaa'}]   ->  [{t:'aaaa'}]
<script>
        let arr = [
            {title:'aaaaa', read:100, hot:true},
            {title:'bbbb', read:100, hot:true},
            {title:'cccc', read:100, hot:true},
            {title:'dddd', read:100, hot:true}
        ];
        
        let newArr = arr.map((item, index, arr)=>{
            let json={}
            json.t = `^_^${item.title}-----`;
            json.r = item.read+200;
            json.hot = item.hot == true &amp;& '真棒!!!';
            return json;
        });

        console.log(newArr);
        
</script>

1.3 arr.filter(): 过滤,过滤一些不合格“元素”, 如果回调函数返回true,就留下来

<script>
        let arr = [
            {title:'aaaaa', read:100, hot:true},
            {title:'bbbb', read:100, hot:false},
            {title:'cccc', read:100, hot:true},
            {title:'dddd', read:100, hot:false}
        ];
        
        let newArr = arr.filter((item, index, arr)=>{
            return item.hot==false;
        });  

        console.log(newArr);
    </script>

1.4 arr.some() 和 arr.every()

arr.some(): 类似查找,  数组里面某一个元素符合条件,返回true
arr.every(): 数组里面所有的元素都要符合条件,才返回true
<script>
        let arr = [1,3,5,7,9,10];

        var b = arr.every((val, index, arr)=>{
            return val%2==1;
        });

        console.log(b);
    </script>
其实他们可以接收两个参数:
    arr.forEach/map...(循环回调函数, this指向谁);
------------------------------------------------------------
arr.reduce()   //从左往右
    求数组的和、阶乘
<script>
        let arr = [1,2,3,4,5,6,7,8,9,10];

        //prev:上一次返回的结果值,cur:当前值
        let res = arr.reduce((prev, cur, index, arr) =>{
            return prev+cur;
        });

        console.log(res);

    </script>
    
arr.reduceRight()  //从右往左
------------------------------------------------------------    

ES2017新增一个运算符:**

Math.pow(2,3)等价于:2 ** 3

======================================================
for....of....:

arr.keys()    数组下标
arr.entries()    数组某一项

for(let val of arr){
    console.log(val);
}

二、数组

2.1 扩展运算符:

...

let arr =[1,2,3];
复制数组:let arr2 = [...arr];

let arr2 = Array.From(arr);

2.2 Array.from

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

@H_168_512@个人观点: 具备 length这个东西,就靠谱
<script>
        let str = 'Strive';

        //let arr = str.split('');
        let arr = Array.from(str);

        console.log(arr);
</script>

Array.of(): 把一组值,转成数组

let arr = Array.of('apple','banana','orange');

console.log(arr);

2.3 find,findIndex,fill

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

<script>
        let arr = [23,900,101,80,100];

        let res = arr.find((val, index, arr) =>{
            return val>1000;
        });

        console.log(res);
</script>

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

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

在ES2016里面新增:

arr.indexOf()
arr.includes()
    str.includes()

三、对象

3.1 对象简洁语法(相当有用)

    <script>
        let name = 'Strive';
        let age = 18;

        let json ={
            name,   //name:name,
            age,     //age:age
            /* showA:function(){
                return this.name;
            } */
            showA(){  //个人建议: 一定注意,不要用箭头函数
                return this.name;
            },
            showB(){
                return this.age;
            }
        };

        console.log(json.showA(), json.showB());

</script>

===>

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

new Vue({
    router,
    App,
    vuex
})

3.2 Object.is()

用来比较两个值是否相等

<script>
        console.log(NaN == NaN); //false

        console.log(Number.isNaN(NaN)); //true

        let b = Object.is(NaN, NaN); //true

        console.log(b);

        
    </script>
Object.is('a','a');

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

Object.is(NaN, NaN); //true

Object.is(+0, -0); //false

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;

对象身上: 计划在ES2018引入

...

let json = {a:3, b:4};
        let json2 = {...json};

四、Promise

承诺,许诺

作用: 解决异步回调问题

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

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

4.1 语法

    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]): 只要有一个成功,就返回

4.2 案例:用户登录 -> 用户信息

<script>
        let status = 1;
        let userLogin = (resolve, reject) =>{
            setTimeout(()=>{
                if(status == 1){
                    resolve({data:'登录成功', msg:'xxx', token:'xxsadfsadfas'});
                }else{
                    reject('失败了');
                }
            },2000);
        };

        let getUserInfo = (resolve, reject) =>{
            setTimeout(()=>{
                if(status == 1){
                    resolve({data:'获取用户信息成功', msg:'asdfasdf', token:'xxsadfsadfas'});
                }else{
                    reject('失败了');
                }
            },1000);
        }

        new Promise(userLogin).then(res=>{
            console.log('用户登录成功');
            return new Promise(getUserInfo);
        }).then(res=>{
            console.log('获取用户信息成功');
            console.log(res);
        })
    </script>

五、模块化

JavaScript不支持模块化

    ruby   require
    python  import

在ES6之前,社区制定一套模块规范:
    Commonjs        主要服务端  nodeJs    require('http')
    AMD            requireJs, curlJs
    CMD            seaJs

ES6出来,统一服务端和客户端模块规范:
    import {xx} ddd

5.1 模块化

注意: 需要放到服务器环境

a). 如何定义模块?
        export  东西
        export const a =12;
        export{
            a as aaa,
            b as banana
        }
        export default 12; //import a 不需要加花括号
b). 如何使用?
        import
        import './modules/1.js'; 
        import {a as a, banana, c} from './modules/2.js'
        import * as modTwo from './modules/2.js';
        import a,[cc,dd} from '/.modules/3.js';
使用模块:
    <script type="module"></script>

5.2 import: 特点

    a). import 可以是相对路径,也可以是绝对路径
        import 'https://code.jquery.COM/jquery-3.3.1.js';
    b). import模块只会导入一次,无论你引入多少次
    c). import './modules/1.js';  如果这么用,相当于引入文件
    d). 有提升效果,import会自动提升到顶部,'首先执行'
<script type="module">
        console.log(a+b);
        import mod,{show, sum, a, b} from './modules/4.js';
    </script>
    e). 导出去模块内容,如果里面有定时器更改,外面也会改动

5.3 import()

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

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

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

    Promise.all([])
<script type="module">
        Promise.all([
            import('./modules/1.js'),
            import('./modules/2.js')
        ]).then(([mod1,mod2])=>{
            console.log(mod1);
            console.log(mod2);
        })
</script>

ES2017加 async await:

'use strict'        以后默认就是严格模式,es6默认严格模式

完!

参考视频资料:ES6经典入门到进阶

脚本宝典总结

以上是脚本宝典为你收集整理的ES6入门到进阶(二):循环、数组、对象全部内容,希望文章能够帮你解决ES6入门到进阶(二):循环、数组、对象所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。