13 個從 ES2021 到 ES2023 實用 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

您最喜歡確定對象是否具有名稱屬性的方法是什麼?

是的,通常有兩種方式,它們有什麼區別呢?

“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

總結

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

最後,感謝你的閱讀。

英文 | https://javascript.plainenglish.io/13-amazing-and-useful-new-javascript-features-from-es2021-to-es2023-5aefc99718e4

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/Zx9H4nupx9Mhb_mcDe3uJQ