13 個(gè)從 ES2021 到 ES2023 實(shí)用JavaScript 新特性技巧
Javascript 變化如此之快,作為前端開發(fā)人員,我們必須通過(guò)不斷學(xué)習(xí)才能跟上它的發(fā)展步伐。
ES2023
ES2023中Javascript有很多有用的數(shù)組方法,比如toSorted,toReversed等。
1.toSorted
你一定用過(guò)數(shù)組的sort方法,我們可以用它來(lái)對(duì)數(shù)組進(jìn)行排序。
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]
數(shù)組通過(guò) sort 方法排序后,其值發(fā)生了變化。如果你不希望數(shù)組本身被重新排序,而是得到一個(gè)全新的數(shù)組,你可以嘗試使用 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 ]
不得不說(shuō),我真的很喜歡這種方法,太棒了。除此之外,我們還可以使用許多類似的方法。
// 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']
最后,數(shù)組有一個(gè)神奇的功能,它被命名為 with。
Array 實(shí)例的 with() 方法是使用括號(hào)表示法更改給定索引值的復(fù)制版本。它返回一個(gè)新數(shù)組,其中給定索引處的元素替換為給定值。
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
相信大家對(duì) array.find 方法并不陌生,我們經(jīng)常用它來(lái)查找符合條件的元素。
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
我想您已經(jīng)猜到了,我們已經(jīng)可以使用 findLastIndex 來(lái)查找數(shù)組末尾的匹配元素了。
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
很久以前,我們只能使用一個(gè)對(duì)象作為 WeakMap 的key。
const w = new WeakMap()
const user = { name: 'fatfish' }
w.set(user, 'medium')
console.log(w.get(user)) // 'medium'
現(xiàn)在我們使用“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
您最喜歡確定對(duì)象是否具有名稱屬性的方法是什么?
是的,通常有兩種方式,它們有什么區(qū)別呢?
- 對(duì)象中的“名稱”
- obj.hasOwnProperty(‘名稱’)
“in”運(yùn)算符
如果指定屬性在指定對(duì)象或其原型鏈中,則 in 運(yùn)算符返回 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 方法返回一個(gè)布爾值,指示對(duì)象是否具有指定的屬性作為其自身的屬性(而不是繼承它)。
使用上面相同的例子
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”已經(jīng)可以過(guò)濾掉原型鏈上的屬性,但在某些情況下并不安全,會(huì)導(dǎo)致程序失敗。
Object.create(null).hasOwnProperty('name')
// Uncaught TypeError: Object.create(...).hasOwnProperty is not a function
Object.hasOwn
不用擔(dān)心,我們可以使用“Object.hasOwn”來(lái)規(guī)避這兩個(gè)問(wèn)題,比“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
當(dāng)我們想要獲取數(shù)組的第 N 個(gè)元素時(shí),我們通常使用 [] 來(lái)獲取。
const array = [ 'fatfish', 'medium', 'blog', 'fat', 'fish' ]
console.log(array[ 1 ], array[ 0 ]) // medium fatfish
哦,這似乎不是什么稀罕事。但是請(qǐng)朋友們幫我回憶一下,如果我們想得到數(shù)組的最后第N個(gè)元素,我們會(huì)怎么做呢?
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
這看起來(lái)很難看,我們應(yīng)該尋求一種更優(yōu)雅的方式來(lái)做這件事。是的,以后請(qǐng)使用數(shù)組的at方法!
它使您看起來(lái)像高級(jí)開發(fā)人員。
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 操作符用于等待一個(gè) 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)
事實(shí)上,在 ES2022 之后,我們可以在模塊的頂層使用 await,這對(duì)于開發(fā)者來(lái)說(shuō)是一個(gè)非常令人高興的新特性。
const getUserInfo = () => {
return new Promise((rs) => {
setTimeout(() => {
rs({
name: 'fatfish'
})
}, 2000)
})
}
const userInfo = await getUserInfo()
console.log('userInfo', userInfo)
8.使用“#”聲明私有屬性
以前我們用“_”來(lái)表示私有屬性,但是不安全,仍然有可能被外部修改。
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
我們可以使用“#”來(lái)實(shí)現(xiàn)真正安全的私有屬性。
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.更容易為類設(shè)置成員變量
除了通過(guò)“#”為類設(shè)置私有屬性外,我們還可以通過(guò)一種新的方式設(shè)置類的成員變量。
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
現(xiàn)在你可以使用下面的方式,使用起來(lái)確實(shí)更方便。
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.有用的數(shù)字分隔符
我們可以使用“_”來(lái)實(shí)現(xiàn)數(shù)字可讀性。這個(gè)真的很酷。
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
當(dāng)然,實(shí)際計(jì)算時(shí)我們可以使用“_”。
const sum = 1000 + 6000_000_000 // 6000001000
11.邏輯或賦值(||=)
邏輯或賦值 (x ||= y) 運(yùn)算符僅在 x 為假時(shí)才賦值。
const obj = {
name: '',
age: 0
}
obj.name ||= 'fatfish'
obj.age ||= 100
console.log(obj.name, obj.age) // fatfish 100
小伙伴們可以看到,當(dāng)x的值為假值時(shí),賦值成功。
它能為我們做什么?
如果“l(fā)yrics”元素為空,則顯示默認(rèn)值:
document.getElementById("lyrics").textContent ||= "No lyrics."
它在這里特別有用,因?yàn)樵夭粫?huì)進(jìn)行不必要的更新,也不會(huì)導(dǎo)致不必要的副作用,例如額外的解析或渲染工作,或失去焦點(diǎn)等。
ES2020
12. 使用“??” 而不是“||”
使用 ”??” 而不是“||”,而是用來(lái)判斷運(yùn)算符左邊的值是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”支持大整數(shù)計(jì)算問(wèn)題
JS 中超過(guò)“Number.MAX_SAFE_INTEGER”的數(shù)字計(jì)算將不保證正確。
例子
Math.pow(2, 53) === Math.pow(2, 53) + 1 // true
// Math.pow(2, 53) => 9007199254740992
// Math.pow(2, 53) + 1 => 9007199254740992
對(duì)于大數(shù)的計(jì)算,我們可以使用“BigInt”來(lái)避免計(jì)算錯(cuò)誤。
BigInt(Math.pow(2, 53)) === BigInt(Math.pow(2, 53)) + BigInt(1) // false
總結(jié)
以上就是我今天想跟你分享全部?jī)?nèi)容,希望對(duì)你有用。