zoukankan      html  css  js  c++  java
  • ES6数组去重与promise执行顺序

    Array.from()方法就是将一个类数组对象或者可遍历对象转换成一个真正的数组。所谓类数组对象,最基本的要求就是具有length属性的对象。

    将一个类数组对象转换为一个真正的数组,必须具备以下条件:

      1、该类数组对象必须具有length属性,用于指定数组的长度。如果没有length属性,那么转换后的数组是一个空数组。

      2、该类数组对象的属性名必须为数值型或字符串型的数字。

      ps: 该类数组对象的属性名可以加引号,也可以不加引号。

    Array.from可以接受三种类型的参数:

    1,Array.from (obj, mapFn)

    obj指的是数组对象、类似数组对象或者是set对象,map指的是对数组中的元素进行处理的方法。
    //将数组中布尔值为false的成员指为0
    Array.from([1, ,2,3,3], x => x || 0) //[1,0,2,3,3]
     
    //将一个类似数组的对象转为一个数组,并在原来的基础上乘以2倍
    let arrayLike = { '0': '2', '1': '4', '2': '5', length: 3 }
    Array.from(arrayLike, x => x*2) //[4,8,10]
     
    //将一个set对象转为数组,并在原来的基础上乘以2倍
    Array.from(new Set([1,2,3,4]), x => x*2) //[2,4,6,8]

    2,Array.from ({length:n}, Fn)

    第一个参数指定了第二个参数执行的次数。可以将各种值转化为真正的数组。
    Array.from({length:3}, () => 'jack') //["jack", "jack", "jack"]
     
    Array.from({length:3}, item => (item = {'name':'shao','age':18})) //[{'name':'shao','age':18}, {'name':'shao','age':18}, {'name':'shao','age':18}]
     
    Array.from({length: 2}, (v, i) => item = {index:i});//生成一个index从0到4的数组对象[{index: 0},{index: 1}]

    3,Array.from(string) 

    接受一个字符串
    Array.from('abc') //['a','b','c']

    new Set() 方法数组去重

    ES6 新增了 Set 这一数据结构,类似于数组,但 Set 的成员具有唯一性。基于这一特性,就非常适合用来做数组去重了。

    function distinct(a, b) {
        return Array.from(new Set([...a, ...b]))
    }

    for...of + Object 方法数组去重

    首先创建一个空对象,然后用 for 循环遍历,利用对象的属性不会重复这一特性,校验数组元素是否重复。

    function distinct(a, b) {
        let arr = a.concat(b)
        let result = []
        let obj = {}
    
        for (let i of arr) {
            if (!obj[i]) {
                result.push(i)
                obj[i] = 1
            }
        }
    
        return result
    }

    对于promise、async和await的执行顺序

    async function async1(){
      console.log('async1 start')
      await async2()
      console.log('async1 end')
    }
    async function async2(){
      console.log('async2')
    }
    console.log('script start')
    setTimeout(function(){
      console.log('setTimeout') 
    },0)  
    async1();
    new Promise(function(resolve){
      console.log('promise1')
      resolve();
    }).then(function(){
      console.log('promise2')
    })
    console.log('script end')

    以上代码的打印顺序依次为:

    script start
    async1 start
    async2
    promise1
    script end
    promise2
    async1 end
    setTimeout

    需要注意的是:

    1. setTimeout定时为0也不是同步马上执行,而是异步执行。
    2. Promise函数会同步执行。
    3. Promise中的resolve执行后,then()不是同步执行,而是异步执行。
  • 相关阅读:
    C++
    Qt简介
    C语言
    C/C++
    swagger2 Illegal DefaultValue null for parameter type integer
    maven包引入问题ClassNotFoundException: org.elasticsearch.client.Cancellable
    mysql自定义排序
    使用node创建服务器 运行vue打包的文件
    rsync实现服务器之间同步目录文件
    将jar包发布到maven的中央仓库细节整理
  • 原文地址:https://www.cnblogs.com/asituhaitang/p/11759930.html
Copyright © 2011-2022 走看看