第七节:ES7之includes、幂等运算符 和 ES8之async/await、Object扩展、String扩展、尾逗号

一. ES7 

1. includes

(1). ES7之前,判断数组中是否包含某个元素,一般用 find方法 或 filter方法。

    // ES7之前
    var array1=['1','2','3','5']
    console.log(array1.find(function(item) {
        return item === '2'
    }))   //2
    console.log(array1.filter(function(item) {
        return item === '2'
    }).length > 0)  //true
    console.log('-----------------------')

(2). ES7中引入includes方法

A. 基本用法

    const arr = ['es6', 'es7', 'es8']
    console.log(arr.includes('es6')) // true
    console.log(arr.includes('es9')) // false

B. 从索引处开始查找(包含该索引的内容)

const arr = ['es6', 'es7', 'es8']
console.log(arr.includes('es7', 1)) // true
console.log(arr.includes('es7', 2)) // false
console.log(arr.includes('es7', -1)) // false
console.log(arr.includes('es7', -2)) // true

C.与indexof比较

['a', 'b', 'c'].includes('a') //true
['a', 'b', 'c'].indexOf('a') > -1 //true

console.log(arr.indexOf('es7')) // 1
console.log(arr.indexOf('es7') > -1) // true

PS:

 两者都是采用===的操作符来作比较的,不同之处在于:对于NaN的处理结果不同。我们知道js中 NaN === NaN 的结果是false, indexOf()也是这样处理的,但是includes()不是这样的。

 如果只想知道某个值是否在数组中存在,而并不关心它的索引位置,建议使用includes()。如果想获取一个值在数组中的位置,那么只能使用indexOf方法。

2. 幂等运算符

(1). ES7之前,需要手写方法

   // 自己封装
    function pow(x, y) {
        let res = 1
        for (let i = 0; i < y; i++) {
            res *= x
        }
        return res
    }
   console.log(pow(2, 10))    //1024
   //或者直接Math.pow
   console.log(Math.pow(2, 10)) // 1024

(2). ES7中引入  **

console.log(2 ** 10) // 1024

 

二. ES8-async/await

1. 说明

 async 和 await 是一种更加优雅的异步编程解决方案,是Promise 的拓展,在我们处理异步的时候,比起回调函数,Promise的then方法会显得较为简洁和清晰,但是在处理多个彼此之间相互依赖的请求的时候,就会显的有些繁琐。这时候,用async/await更加优雅。

我们知道 JavaScript 是单线程的,使用 Promise 之后可以让我们书写异步操作更加简单,而 async 是让我们写起 Promise 像同步操作

2. 基本语法

(1). 前面添加了async的函数在执行后都会自动返回一个Promise对象:

   async function foo() {
        return 'imooc' // Promise.resolve('imooc')
    
        // let res =  Promise.resolve('imooc')
        // console.log(res)
    }
    console.log(foo()) // Promise
    foo()

(2). await后面需要跟异步操作,不然就没有意义,而且await后面的Promise对象不必写then,因为await的作用之一就是获取后面Promise对象成功状态传递出来的参数。

function timeout() {
    return new Promise(resolve => {
        setTimeout(() => {
            console.log(1)
            resolve() // resolve('success')
        }, 1000)
    })
}

// 不加async和await是2、1   加了是1、2
async function foo() {
    await timeout() // let res = await timeout() res是success
    console.log(2)
}
foo()

3. 场景1-多次发送ajax请求 (重点)

 我们需要发送多个请求,而后面请求的发送总是需要依赖上一个请求返回的数据。对于这个问题,我们既可以用的Promise的链式调用来解决,也可以用async/await来解决,然而后者会更简洁些。

// 把ajax封装成模块
import ajax from './ajax'

function request(url) {
    return new Promise(resolve => {
        ajax(url, res => {
            resolve(res)
        })
    })
}
async function getData() {
    let res1 = await request('static/a.json')
    console.log(res1)
    let res2 = await request('static/b.json')
    console.log(res2)
    let res3 = await request('static/c.json')
    console.log(res3)
}
getData()

 补充1个实际代码:

await拿到返回值,解构赋值给data

 login() {
        // 2.1 先对整个form表单进行规则校验
        this.$refs.loginFormRef.validate(async valid => {
          console.log(valid)
          if (!valid) return
          // 2.2 校验通过,发送请求
          const {
            data: res
          } = await this.$http.post('login', this.loginForm)
          if (res.meta.status !== 200) return this.$message.error('登录失败!')
          this.$message.success('登录成功')
          // 2.3. 将登录成功之后的 token,保存到客户端的 sessionStorage 中
          // 2.3.1 项目中出了登录之外的其他API接口,必须在登录之后才能访问
          // 2.3.2 token 只应在当前网站打开期间生效,所以将 token 保存在 sessionStorage 中
          window.sessionStorage.setItem('token', res.data.token)
          // 2.4  通过编程式导航跳转到后台主页,路由地址是 /home
          this.$router.push('/home')
        })
      }
    }

 

三. ES8-Object扩展

1. ES8之前获取对象的key 、value

const obj = {
        name: 'imooc',
        web: 'www.imooc.com',
        course: 'es'
    }
    // 获取key值
    console.log(Object.keys(obj))   //[ 'name', 'web', 'course' ]
    // 获取内容值
    const res = Object.keys(obj).map(key => obj[key])
    console.log(res)    //[ 'imooc', 'www.imooc.com', 'es' ]

2. ES8新增 Object.values()

 用于获取values值

    const obj = {
        name: 'imooc',
        web: 'www.imooc.com',
        course: 'es'
    }
    console.log(Object.values(obj))  //[ 'imooc', 'www.imooc.com', 'es' ]

3. ES8新增 Object.entries()

 Object.entries()方法返回一个给定对象自身可枚举属性的键值对数组,其排列与使用 for...in 循环遍历该对象时返回的顺序一致。(区别在于 for-in 循环也枚举原型链中的属性)

    let grade = {
        'lilei': 98,
        'hanmei': 87
    }
    
    for (let [k, v] of Object.entries(grade)) {
        console.log(k, v)
        // lilei 98
        // hanmei 87
    }

4. ES8新增 Object.getOwnPropertyDescriptors()

  还是上述那个对象,这里有 key 和 value,上边的代码把所有的 key、value 遍历出来,如果我们不想让 Lima 这个属性和值被枚举怎么办?

Object.defineProperty(data, 'Lima', {
    enumerable: false
})

Object.entries(data).map(([city, temp]) => {
    console.log( `City: ${city.padEnd(16)} Weather: ${temp}` )
    // City: Portland         Weather: 78/50
    // City: Dublin           Weather: 88/52
})

 

四. ES8-String扩展

 1. padStart()

  把指定字符串填充到字符串头部,返回新字符串。

 案例:

    const str = 'imooc'
    console.log(str.padStart(8, 'x'))
    console.log(str.padStart(8))
    console.log(str.padEnd(8, 'y'))

 

场景1:日期格式化

 希望把当前日期格式化城:yyyy-mm-dd的格式:

    const now = new Date()
    const year = now.getFullYear()
    const month = (now.getMonth() + 1).toString().padStart(2, '0')
    const day = (now.getDate()).toString().padStart(2, '0')
    console.log(year, month, day)                //2021 04 25
    console.log( `${year}-${month}-${day}` )   //2021-04-25

场景2:数字替换

// 数字替换,比如手机号,身份证号
const tel = '13012345678'
const newTel = tel.slice(-4).padStart(tel.length, '*')
console.log(newTel) // *******5678

 2. padEnd()

  方法会用一个字符串填充当前字符串(如果需要的话则重复填充),返回填充后达到指定长度的字符串。从当前字符串的末尾(右侧)开始填充。 语法:

 

 

 基本用法:

const str1 = 'I am learning es in imooc'
console.log(str1.padEnd(30, '.'))
// I am learning es in imooc.....

const str2 = '200'
console.log(str2.padEnd(5))
// "200  "
View Code

场景1:时间戳统一长度

  在JS前端我们处理时间戳的时候单位都是ms毫秒,但是,后端同学返回的时间戳则不一样是毫秒,可能只有10位,以s秒为单位。所以,我们在前端处理这个时间戳的时候,保险起见,要先做一个13位的补全,保证单位是毫秒。

// 伪代码
console.log(new Date().getTime()) // 时间戳 13位的
timestamp = +String(timestamp).padEnd(13, '0')

 

五. ES8-尾逗号

1. ES8之前 

 此前,函数定义和调用时,都不允许最后一个参数后面出现逗号。

   //定义函数
    function clownsEverywhere(param1, param2) {
       console.log(`${param1},${param2}`)
    }
    // 调用函数
    clownsEverywhere('foo','bar')

2. ES8允许尾巴逗号

   //定义函数
    function clownsEverywhere(param1, param2,) {
       console.log(`${param1},${param2}`)
    }
    // 调用函数
    clownsEverywhere('foo','bar',)

 

 

 

!

  • 作       者 : Yaopengfei(姚鹏飞)
  • 博客地址 : http://www.cnblogs.com/yaopengfei/
  • 声     明1 : 如有错误,欢迎讨论,请勿谩骂^_^。
  • 声     明2 : 原创博客请在转载时保留原文链接或在文章开头加上本人博客地址,否则保留追究法律责任的权利。
 
posted @ 2021-04-25 15:00  Yaopengfei  阅读(152)  评论(1编辑  收藏  举报