1.2.1 - ECMAScript 新特性

122 阅读2分钟

★ ES2015 概述

  • 对原有语法进⾏增强【解构、展开、参数默认值、模板字符串等待】

  • 解决原有语法上的⼀些问题或者缺陷 【let const】

  • 全新的对象、全新的⽅法、全新的功能【promise proxy】

  • 全新的数据类型和数据结构【symbol set map】

let与块级作用域

块级作用域就是大括号{},var即使再块级作用域里面定义的也是全局变量,只有let再块级作用域里面才是块级作用域,解决块级作用域循环嵌套问题

变量提升

const

const是不允许重新指向新的内存地址,

不用var 默认使用const 配合用let

解构

// const name = 'tom'
// const { name: objName = 'jack' } = obj
// console.log(objName)

const { log } = console
log('foo')
log('bar')
log('123')

模板字符串

// 允许换行
// const str = `hello es2015,

// this is a \`string\``

// 可以通过 ${} 插入表达式,表达式的执行结果将会输出到对应位置
const msg = `hey, ${name} --- ${1 + 2} ---- ${Math.random()}`


// 带标签的模板字符串

// 模板字符串的标签就是一个特殊的函数,
// 使用这个标签就是调用这个函数
// const str = console.log`hello world`

const name = 'tom'
const gender = false

function myTagFunc (strings, name, gender) {
  // console.log(strings, name, gender)
  // return '123'
  const sex = gender ? 'man' : 'woman'
  return strings[0] + name + strings[1] + sex + strings[2]
}

const result = myTagFunc`hey, ${name} is a ${gender}.`

console.log(result)

字符串扩展方法

  // message.startsWith('Error')
  // message.endsWith('.')
  message.includes('foo')

★ ES2016

Array.prototype.includes

// const arr = ['foo', 1, NaN, false]

// 找到返回元素下标
// console.log(arr.indexOf('foo'))
// 找不到返回 -1
// console.log(arr.indexOf('bar'))
// 无法找到数组中的 NaN
// console.log(arr.indexOf(NaN))

// 直接返回是否存在指定元素
// console.log(arr.includes('foo'))
// 能够查找 NaN
// console.log(arr.includes(NaN))

指数运算符

console.log(Math.pow(2, 10))
console.log(2 ** 10)

★ ES2017

const obj = {
  foo: 'value1',
  bar: 'value2'
}

Object.values

console.log(Object.values(obj))
// [ 'value1', 'value2' ]

Object.entries

console.log(Object.entries(obj))
 // [ [ 'foo', 'value1' ], [ 'bar', 'value2' ] ]
 
for (const [key, value] of Object.entries(obj)) {
  console.log(key, value)
}

// foo value1
// bar value2

console.log(new Map(Object.entries(obj)))
//Map { 'foo' => 'value1', 'bar' => 'value2' }

Object.getOwnPropertyDescriptors 获取对象当中属性的完整描述信息,配合get set去使用

const p1 = {
  firstName: 'Lei',
  lastName: 'Wang',
  get fullName () {
    return this.firstName + ' ' + this.lastName
  }
}


const descriptors = Object.getOwnPropertyDescriptors(p1)

const p2 = Object.defineProperties({}, descriptors)
p2.firstName = 'zce'
console.log(p2.fullName) 
// zce Wang
     

String.prototype.padStart / String.prototype.padEnd

const books = {
  html: 5,
  css: 16,
  javascript: 128
}

for (const [name, count] of Object.entries(books)) {
  console.log(`${name.padEnd(16, '-')}|${count.toString().padStart(3, '0')}`)
}
html------------|005
css-------------|016
javascript------|128

在函数参数中添加尾逗号

function foo (
  bar,
  baz,
) {}

const arr = [
  100,
  200,
  300,
]