ES7-12常见基本知识点的基本使用

342 阅读7分钟

学习了coderwhy的JavaScript高级语法视频课的笔记

如有错误或者不合适的地方,敬请见谅,欢迎指出和拓展,谢谢各位了

1、ES7

  • Array Includes
    • 在ES7之前,如果我们想判断一个数组中是否包含某个元素,需要通过indexOf获取结果,并且判断是否为 -1;
    • 在ES7中,我们可以通过includes来判断一个数组中是否包含一个指定的元素,根据情况,如果包含则返回 true, 否则返回false。
const names = ['abc', 'cba', 'nba', 'mba', NaN]

if (names.indexOf('cba') !== -1) {
  console.log('包含abc元素') //包含abc元素
}

// ES7 ES2016
// arr.includes(searchElement, fromIndex)。fromIndex可选。从该索引处开始查找searchElement;
// 如果为负值,则按升序从 array.length + fromIndex 的索引开始搜索。默认为 0。
if (names.includes('cba', 2)) {
  console.log('包含abc元素')
}

//不能查找NaN
if (names.indexOf(NaN) !== -1) {
  console.log('包含NaN')
}

if (names.includes(NaN)) {
  console.log('包含NaN-2') //包含NaN-2
}
  • 指数(乘方) exponentiation运算符
    • 在ES7之前,计算数字的乘方需要通过Math.pow方法来完成;
    • 在ES7中,增加了 ** 运算符,可以对数字来计算乘方。
const result1 = Math.pow(2, 3)

// ES7: **
const result2 = 2 ** 3
console.log(result1, result2) //8 8

2、ES8

  • Object values
    • 之前我们可以通过 Object.keys 获取一个对象所有的key,在ES8中提供了 Object.values 来获取所有的value值。
const obj = {
  name: 'why',
  age: 18
}

console.log(Object.keys(obj)) //[ 'name', 'age' ]
console.log(Object.values(obj)) //[ 'why', 18 ]

// 用的非常少
console.log(Object.values(['abc', 'cba', 'nba'])) //[ 'abc', 'cba', 'nba' ]
console.log(Object.values('abc')) //[ 'a', 'b', 'c' ]
  • Object entries
    • 通过Object.entries 可以获取到一个数组,数组中会存放可枚举属性的键值对数组。
const obj = {
  name: 'why',
  age: 18
}

console.log(Object.entries(obj)) //[ [ 'name', 'why' ], [ 'age', 18 ] ]

const objEntries = Object.entries(obj)
objEntries.forEach(item => {
  console.log(item[0], item[1])
  // name why
  // age 18
})

console.log(Object.entries(['abc', 'cba', 'nba'])) //[ [ '0', 'abc' ], [ '1', 'cba' ], [ '2', 'nba' ] ]
console.log(Object.entries('abc')) //[ [ '0', 'a' ], [ '1', 'b' ], [ '2', 'c' ] ]
  • String Padding
    • 某些字符串我们需要对其进行前后的填充,来实现某种格式化效果,ES8中增加了 padStartpadEnd 方法,分 别是对字符串的首尾进行填充的。
const message = 'Hello World'

const newMessage = message.padStart(15, '*').padEnd(20, '-')
console.log(newMessage) //****Hello World-----

// 案例
const cardNumber = '321324234242342342341312'
// array.slice(start, end),不包含end,-1代表最后一个
const lastFourCard = cardNumber.slice(-4)
const finalCard = lastFourCard.padStart(cardNumber.length, '*')
console.log(finalCard) //********************1312
  • Trailing Commas
    • 在ES8中,我们允许在函数定义和调用时多加一个逗号。
function foo(m, n,) {}

foo(20, 30,)
  • Object Descriptors
    • ES8中增加了另一个对对象的操作是 Object.getOwnPropertyDescriptors。
const a = {
  name: 'why'
}

console.log(Object.getOwnPropertyDescriptors(a))
//   {
//     name: {
//     value: 'why',
//     writable: true,
//     enumerable: true,
//     configurable: true
//     }
//   }

3、ES9

  • Object spread operators
const a = {
  name: 'why',
  age: 18,
  address: 'gd'
}

const b = { ...a }

console.log(b) //{ name: 'why', age: 18, address: 'gd' }

4、ES10

  • flat()
    • flat() 方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。
// flat的使用
const nums = [10, 20, [2, 9], [[30, 40], [10, 45]], 78, [55, 88]]
const newNums = nums.flat()
console.log(newNums)// [ 10, 20, 2, 9, [ 30, 40 ], [ 10, 45 ], 78, 55, 88 ]

const newNums2 = nums.flat(2)
console.log(newNums2)// [10, 20,  2,  9, 30,40, 10, 45, 78, 55,88]
  • flatMap() 方法首先使用映射函数映射每个元素,然后将结果压缩成一个新数组
    • 注意一:flatMap是先进行map操作,再做flat的操作
    • 注意二:flatMap中的flat相当于深度为1。
// 1.flatMap的使用
const nums2 = [10, 20, 30]
const newNums3 = nums2.flatMap(item => {
  return item * 2
})
const newNums4 = nums2.map(item => {
  return item * 2
})

console.log(newNums3) //[ 20, 40, 60 ]
console.log(newNums4) //[ 20, 40, 60 ]

// 2.flatMap的应用场景(先进行map操作,再做flat的操作)
const messages = ['Hello World', 'hello lyh', 'my name is coderwhy']
const words = messages.flatMap(item => {
  return item.split(' ')
})
console.log(words)
// [
//    'Hello', 'World',
//    'hello', 'lyh',
//    'my',    'name',
//    'is',    'coderwhy'
// ]

const messages2 = ['Hello World', 'hello lyh', 'my name is coderwhy']
const words2 = messages.map(item => {
  return item.split(' ')
})
console.log(words2)
// [
//    [ 'Hello', 'World' ],
//    [ 'hello', 'lyh' ],
//    [ 'my', 'name', 'is', 'coderwhy' ]
// ]
  • Object fromEntries
    • 在前面,我们可以通过 Object.entries 将一个对象转换成 entries。如果我们有一个entries了,ES10提供了Object.formEntries来完成转换成对象
const obj = {
  name: 'why',
  age: 18,
  height: 1.88
}

const entries = Object.entries(obj)
console.log(entries) //[ [ 'name', 'why' ], [ 'age', 18 ], [ 'height', 1.88 ] ]

// 以前的做法
const newObj = {}
for (const entry of entries) {
  newObj[entry[0]] = entry[1]
}
console.log(newObj) //{ name: 'why', age: 18, height: 1.88 }

// 1.ES10中新增了Object.fromEntries方法
const newObj2 = Object.fromEntries(entries)
console.log(newObj2) //{ name: 'why', age: 18, height: 1.88 }

// 2.Object.fromEntries的应用场景
const queryString = 'name=why&age=18&height=1.88'

// URLSearchParams 接口定义了一些实用的方法来处理 URL 的查询字符串。
// 一个实现了 URLSearchParams 的对象可以直接用在 for...of 结构中,例如下面两行是相等的:
// for (const [key, value] of mySearchParams) {}
// for (const [key, value] of mySearchParams.entries()) {}
const queryParams = new URLSearchParams(queryString)

for (const param of queryParams) {
  console.log(param)
  // [ 'name', 'why' ]
  // [ 'age', '18' ]
  // [ 'height', '1.88' ]
}

const paramObj = Object.fromEntries(queryParams)
console.log(paramObj) //{ name: 'why', age: '18', height: '1.88' }
  • trimStart trimEnd
    • 去除一个字符串首尾的空格,我们可以通过trim方法。单独去除前面或者后面,pES10中给我们提供了trimStart和trimEnd。
const message = '    Hello World    '

console.log(message.trim())// 去除两边空格
console.log(message.trimStart())// 去除前边空格
console.log(message.trimEnd())// 去除后边空格
  • Symbol description
const a = Symbol('aaa')

console.log(a.description) //aaa

5、ES11

  • BigInt
    • 在早期的JavaScript中,我们不能正确的表示过大的数字,大于MAX_SAFE_INTEGER的数值,表示的可能是不正确的;
    • 那么ES11中,引入了新的数据类型BigInt,用于表示大的整数,BigInt的表示方法是在数值的后面加上n。
// ES11之前 max_safe_integer
const maxInt = Number.MAX_SAFE_INTEGER
console.log(maxInt) // 9007199254740991
console.log(maxInt + 1) //9007199254740992
console.log(maxInt + 2) //9007199254740992

// ES11之后: BigInt
const bigInt = 900719925474099100n
console.log(bigInt + 10n) //900719925474099110n

const num = 100
console.log(bigInt + BigInt(num)) //900719925474099200n

// 不能保证安全的、正确的
const smallNum = Number(bigInt)
console.log(smallNum) //900719925474099100
  • Nullish Coalescing Operator
    • ES11,Nullish Coalescing Operator增加了空值合并操作符。
// ES11: 空值合并运算 ??
const foo = ''
const bar = foo || 'default value'
const bar2 = foo ?? 'defualt value'

console.log(bar) //default value
console.log(bar2) //''
  • Optional Chaining
    • 可选链也是ES11中新增一个特性,主要作用是让我们的代码在进行null和undefined判断时更加清晰和简洁。
const info = {
  name: 'why'
  // friend: {
  //   girlFriend: {
  //     name: "hmm"
  //   }
  // }
}

// 以前要先判断是否存在的方法,不让报错
if (info && info.friend && info.friend.girlFriend) {
  console.log(info.friend.girlFriend.name)
}

// ES11提供了可选链(Optional Chainling)
console.log(info.friend?.girlFriend?.name) //undefined
  • Global This
  • 在之前我们希望获取JavaScript环境的全局对象,不同的环境获取的方式是不一样的:
    • 比如在浏览器中可以通过this、window来获取;
    • 比如在Node中我们需要通过global来获取;
  • 那么在ES11中对获取全局对象进行了统一的规范:globalThis。
// 获取某一个环境下的全局对象(Global Object)

// 在浏览器下
// console.log(window)
// console.log(this)

// 在node下
// console.log(global)

// ES11
console.log(globalThis)
  • for..in标准化
    • 在ES11之前,虽然很多浏览器支持for...in来遍历对象类型,但是并没有被ECMA标准化;在ES11中,对其进行了标准化,for...in是用于遍历对象的key的。
// for...in 标准化: ECMA
const obj = {
  name: 'why',
  age: 18
}

for (const item in obj) {
  console.log(item)
  // name
  // age
}

6、ES12

  • FinalizationRegistry 对象可以让你在对象被垃圾回收时请求一个回调。
    • FinalizationRegistry 提供了这样的一种方法:当一个在注册表中注册的对象被回收时,请求在某个时间点上调用一个清理回调。(清理回调有时被称为 finalizer );
    • 你可以通过调用register方法,注册任何你想要清理回调的对象,传入该对象和所含的值;
// ES12: FinalizationRegistry类
const finalRegistry = new FinalizationRegistry(value => {
  console.log('注册在finalRegistry的对象, 某一个被销毁', value)
})

let obj = { name: 'why' }
let info = { age: 18 }

finalRegistry.register(obj, 'obj')
finalRegistry.register(info, 'value')

obj = null
info = null
  • WeakRefs
    • 如果我们默认将一个对象赋值给另外一个引用,那么这个引用是一个强引用,如果我们希望是一个弱引用的话,可以使用WeakRef。
// ES12: WeakRef类
// WeakRef.prototype.deref:
// > 如果原对象没有销毁, 那么可以获取到原对象
// > 如果原对象已经销毁, 那么获取到的是undefined
const finalRegistry = new FinalizationRegistry(value => {
  console.log('注册在finalRegistry的对象, 某一个被销毁', value)
})

let obj = { name: 'why' }
let info = new WeakRef(obj)

finalRegistry.register(obj, 'obj')

obj = null

setTimeout(() => {
  console.log(info.deref()?.name) //undefined
  console.log(info.deref() && info.deref().name) //undefined
}, 20000)
  • logical assignment operators
// 1.||= 逻辑或赋值运算
let message = 'hello world'
// message = message || 'default value'
message ||= 'default value'
console.log(message) //hello world

// 2.&&= 逻辑与赋值运算
// &&
const obj = {
  name: 'why',
  foo: function () {
    console.log('foo函数被调用')
  }
}

obj.foo && obj.foo() //foo函数被调用

// &&=
let info = {
  name: 'why'
}

// // 1.判断info
// // 2.有值的情况下, 取出info.name
// // info = info && info.name
info &&= info.name
console.log(info) //why

// 3.??= 逻辑空赋值运算
let message2 = ''
message2 ??= 'default value'
console.log(message2) //''
  • Numeric Separator
const s = 1_000_000_000

console.log(s) //1000000000
  • String.replaceAll
const a = 'aaabbb'

console.log(a.replace('a', 'c')) //caabbb
console.log(a.replaceAll('a', 'c')) //cccbbb