13 个从 ES2021 到 ES2023 实用JavaScript 新特性技巧

开发 前端
Javascript 变化如此之快,作为前端开发人员,我们必须通过不断学习才能跟上它的发展步伐。

Javascript 变化如此之快,作为前端开发人员,我们必须通过不断学习才能跟上它的发展步伐。

因此,今天这篇文章将分享的13个从 ES2021 到 ES2023的JavaScript新特性技巧,希望对你有所帮助。

ES2023

ES2023中Javascript有很多有用的数组方法,比如toSorted,toReversed等。

1.toSorted

你一定用过数组的sort方法,我们可以用它来对数组进行排序。

const array = [ 1, 2, 4, -5, 0, -1 ]
const array2 = array.sort((a, b) => a - b)


console.log(array2) // [-5, -1, 0, 1, 2, 4]
console.log(array) // [-5, -1, 0, 1, 2, 4]

数组通过 sort 方法排序后,其值发生了变化。如果你不希望数组本身被重新排序,而是得到一个全新的数组,你可以尝试使用 array.toSorted 方法。

const array = [ 1, 2, 4, -5, 0, -1 ]
const array2 = array.toSorted((a, b) => a - b)


console.log(array2) // [-5, -1, 0, 1, 2, 4]
console.log(array) // [ 1, 2, 4, -5, 0, -1 ]

不得不说,我真的很喜欢这种方法,太棒了。除此之外,我们还可以使用许多类似的方法。

// toReversed
const reverseArray = [ 1, 2, 3 ]
const reverseArray2 = reverseArray.toReversed()


console.log(reverseArray) // [1, 2, 3]
console.log(reverseArray2) // [3, 2, 1]
// toSpliced
const spliceArray = [ 'a', 'b', 'c' ]
const spliceArray2 = spliceArray.toSpliced(1, 1,  'fatfish')
console.log(spliceArray2) // ['a', 'fatfish', 'c']
console.log(spliceArray) // ['a', 'b', 'c']

最后,数组有一个神奇的功能,它被命名为 with。

Array 实例的 with() 方法是使用括号表示法更改给定索引值的复制版本。它返回一个新数组,其中给定索引处的元素替换为给定值。

const array = [ 'a', 'b', 'c' ]
const withArray = array.with(1, 'fatfish')


console.log(array) // ['a', 'b', 'c']
console.log(withArray) // ['a', 'fatfish', 'c']

2.findLast

相信大家对 array.find 方法并不陌生,我们经常用它来查找符合条件的元素。

const array = [ 1, 2, 3, 4 ] 
const targetEl = array.find((num) => num > 2) // 3

find方法是从后往前查找符合条件的元素,如果我们想从后往前查找符合条件的元素怎么办?是的,你可以选择 array.findLast

const array = [ 1, 2, 3, 4 ] 
const targetEl = array.findLast((num) => num > 2) // 4

3.findLastIndex

我想您已经猜到了,我们已经可以使用 findLastIndex 来查找数组末尾的匹配元素了。

const array = [ 1, 2, 3, 4 ] 
const index = array.findIndex((num) => num > 2) // 2
const lastIndex = array.findLastIndex((num) => num > 2) // 3

4.WeakMap支持使用Symbol作为key

很久以前,我们只能使用一个对象作为 WeakMap 的key。

const w = new WeakMap()
const user = { name: 'fatfish' }


w.set(user, 'medium')
console.log(w.get(user)) // 'medium'

现在我们使用“Symbol”作为“WeakMap”的key。

const w = new WeakMap()
const user = Symbol('fatfish')


w.set(user, 'medium')
console.log(w.get(user)) // 'medium'

ES2022

5.Object.has

您最喜欢确定对象是否具有名称属性的方法是什么?

是的,通常有两种方式,它们有什么区别呢?

  • 对象中的“名称”
  • obj.hasOwnProperty(‘名称’)

“in”运算符

如果指定属性在指定对象或其原型链中,则 in 运算符返回 true。

const Person = function (age) {
  this.age = age
}


Person.prototype.name = 'fatfish'
const p1 = new Person(24)
console.log('age' in p1) // true 
console.log('name' in p1) // true  pay attention here

obj.hasOwnProperty

hasOwnProperty 方法返回一个布尔值,指示对象是否具有指定的属性作为其自身的属性(而不是继承它)。

使用上面相同的例子

const Person = function (age) {
  this.age = age
}


Person.prototype.name = 'fatfish'
const p1 = new Person(24)
console.log(p1.hasOwnProperty('age')) // true 
console.log(p1.hasOwnProperty('name')) // fasle  pay attention here

也许“obj.hasOwnProperty”已经可以过滤掉原型链上的属性,但在某些情况下并不安全,会导致程序失败。

Object.create(null).hasOwnProperty('name')
// Uncaught TypeError: Object.create(...).hasOwnProperty is not a function

Object.hasOwn

不用担心,我们可以使用“Object.hasOwn”来规避这两个问题,比“obj.hasOwnProperty”方法更方便、更安全。

let object = { age: 24 }


Object.hasOwn(object, 'age') // true
let object2 = Object.create({ age: 24 })
Object.hasOwn(object2, 'age') // false  The 'age' attribute exists on the prototype
let object3 = Object.create(null)
Object.hasOwn(object3, 'age') // false an object that does not inherit from "Object.prototype"

6.array.at

当我们想要获取数组的第 N 个元素时,我们通常使用 [] 来获取。

const array = [ 'fatfish', 'medium', 'blog', 'fat', 'fish' ]


console.log(array[ 1 ], array[ 0 ]) // medium fatfish

哦,这似乎不是什么稀罕事。但是请朋友们帮我回忆一下,如果我们想得到数组的最后第N个元素,我们会怎么做呢?

const array = [ 'fatfish', 'medium', 'blog', 'fat', 'fish' ]
const len = array.length


console.log(array[ len - 1 ]) // fish
console.log(array[ len - 2 ]) // fat
console.log(array[ len - 3 ]) // blog

这看起来很难看,我们应该寻求一种更优雅的方式来做这件事。是的,以后请使用数组的at方法!

它使您看起来像高级开发人员。

const array = [ 'fatfish', 'medium', 'blog', 'fat', 'fish' ]


console.log(array.at(-1)) // fish
console.log(array.at(-2)) // fat
console.log(array.at(-3)) // blog

7.在模块的顶层使用“await”

 await 操作符用于等待一个 Promise 并获取它的 fulfillment 值。

const getUserInfo = () => {
  return new Promise((rs) => {
    setTimeout(() => {
      rs({
        name: 'fatfish'
      })
    }, 2000)
  })
}
// If you want to use await, you must use the async function.
const fetch = async () => {
  const userInfo = await getUserInfo()
  console.log('userInfo', userInfo)
}


fetch()
// SyntaxError: await is only valid in async functions
const userInfo = await getUserInfo()
console.log('userInfo', userInfo)

事实上,在 ES2022 之后,我们可以在模块的顶层使用 await,这对于开发者来说是一个非常令人高兴的新特性。

const getUserInfo = () => {
  return new Promise((rs) => {
    setTimeout(() => {
      rs({
        name: 'fatfish'
      })
    }, 2000)
  })
}


const userInfo = await getUserInfo()
console.log('userInfo', userInfo)

8.使用“#”声明私有属性

以前我们用“_”来表示私有属性,但是不安全,仍然有可能被外部修改。

class Person {
  constructor (name) {
    this._money = 1
    this.name = name
  }


  get money () {
    return this._money
  }
  set money (money) {
    this._money = money
  }
  showMoney () {
    console.log(this._money)
  }
}


const p1 = new Person('fatfish')
console.log(p1.money) // 1
console.log(p1._money) // 1
p1._money = 2 // Modify private property _money from outside
console.log(p1.money) // 2
console.log(p1._money) // 2

我们可以使用“#”来实现真正安全的私有属性。

class Person {
  #money=1
  constructor (name) {
    this.name = name
  }
  get money () {
    return this.#money
  }
  set money (money) {
    this.#money = money
  }
  showMoney () {
    console.log(this.#money)
  }
}
const p1 = new Person('fatfish')
console.log(p1.money) // 1
// p1.#money = 2 // We cannot modify #money in this way
p1.money = 2
console.log(p1.money) // 2
console.log(p1.#money) // Uncaught SyntaxError: Private field '#money' must be declared in an enclosing class

9.更容易为类设置成员变量

除了通过“#”为类设置私有属性外,我们还可以通过一种新的方式设置类的成员变量。

class Person {
  constructor () {
    this.age = 1000
    this.name = 'fatfish'
  }


  showInfo (key) {
    console.log(this[ key ])
  }
}
const p1 = new Person()
p1.showInfo('name') // fatfish
p1.showInfo('age') // 1000

现在你可以使用下面的方式,使用起来确实更方便。

class Person {
  age = 1000
  name = 'fatfish'


  showInfo (key) {
    console.log(this[ key ])
  }
}
const p1 = new Person()
p1.showInfo('name') // fatfish
p1.showInfo('age') // 1000

ES2021

10.有用的数字分隔符

我们可以使用“_”来实现数字可读性。这个真的很酷。

const sixBillion = 6000000000
// It is very difficult to read
const sixBillion2 = 6000_000_000
// It's cool and easy to read
console.log(sixBillion2) // 6000000000

当然,实际计算时我们可以使用“_”。

const sum = 1000 + 6000_000_000 // 6000001000

11.逻辑或赋值(||=)

逻辑或赋值 (x ||= y) 运算符仅在 x 为假时才赋值。

const obj = {
  name: '',
  age: 0
}


obj.name ||= 'fatfish'
obj.age ||= 100
console.log(obj.name, obj.age) // fatfish 100

小伙伴们可以看到,当x的值为假值时,赋值成功。

它能为我们做什么?

如果“lyrics”元素为空,则显示默认值:

document.getElementById("lyrics").textContent ||= "No lyrics."

它在这里特别有用,因为元素不会进行不必要的更新,也不会导致不必要的副作用,例如额外的解析或渲染工作,或失去焦点等。

ES2020

12. 使用“??” 而不是“||”

使用 ”??” 而不是“||”,而是用来判断运算符左边的值是null还是undefined,然后返回右边的值。

const obj = {
  name: 'fatfish',
  nullValue: null,
  zero: 0,
  emptyString: '',
  falseValue: false,
}


console.log(obj.age ?? 'some other default') // some other default
console.log(obj.age || 'some other default') // some other default


console.log(obj.nullValue ?? 'some other default') // some other default
console.log(obj.nullValue || 'some other default') // some other default
console.log(obj.zero ?? 0) // 0
console.log(obj.zero || 'some other default') // some other default


console.log(obj.emptyString ?? 'emptyString') // ''
console.log(obj.emptyString || 'some other default') // some other default


console.log(obj.falseValue ?? 'falseValue') // false
console.log(obj.falseValue || 'some other default') // some other default

13.使用“BigInt”支持大整数计算问题

JS 中超过“Number.MAX_SAFE_INTEGER”的数字计算将不保证正确。

例子

Math.pow(2, 53) === Math.pow(2, 53) + 1 // true
// Math.pow(2, 53) => 9007199254740992
// Math.pow(2, 53) + 1 => 9007199254740992

对于大数的计算,我们可以使用“BigInt”来避免计算错误。

BigInt(Math.pow(2, 53)) === BigInt(Math.pow(2, 53)) + BigInt(1) // false

总结

以上就是我今天想跟你分享全部内容,希望对你有用。

责任编辑:华轩 来源: web前端开发
相关推荐

2023-11-24 08:31:03

ECMAScriptES2021

2023-01-31 07:36:25

JavaScript数组缓冲

2023-04-19 15:26:52

JavaScriptES13开发

2022-08-05 13:14:25

ES2022JavaScript代码

2023-07-11 09:07:49

数组Promise方法

2021-09-04 05:00:26

ESES2021ES12

2021-01-25 14:20:24

ES2021前端代码

2020-11-04 11:05:38

JavaScript新特性前端

2023-06-06 07:50:50

Symbol类型ECMAScript

2021-03-15 08:15:42

ES2021语言开发

2020-07-01 07:58:20

ES6JavaScript开发

2022-05-25 07:22:07

ES12JavaScript语言

2020-11-23 11:34:52

ES6

2009-12-14 18:10:21

Shell特性技巧

2019-12-11 09:00:00

ES7ES8ES9

2022-11-01 15:57:44

2018-07-16 16:10:03

前端JavaScript面向对象

2024-02-19 10:15:37

JavaScript正则表达式ECMAScript

2023-11-23 10:21:11

ECMAScriptJavaScript

2022-07-26 09:02:15

ES6ES13ECMAScript
点赞
收藏

51CTO技术栈公众号