ざっくりと ES2018 のおさらいをしたい人向け。オカタい説明は mdn さんあたりにおまかせするとして、ゆるっとざっくり気楽にサクッとコードベースでおさらい。ES2018 は for-await-ofの追加、正規表現周りの調整、Promiseにfinallyの追加、テンプレートリテラルが見直されたよ。
最小限で動かすだけならこれだけでおっけいです。ここらへんの準備も面倒ならば codepen だの JSFiddle だの REPL だのを使ってもおk
es2018 は以下のような機能が追加されている(参考 Wikipedia ECMAScript)
オブジェクトに対するスプレッド構文、非同期イテレーション、Promise.prototype.finally、正規表現への機能追加
非同期イテレーションである for-await-of に関しては、今日の時点で ESLint 非推奨 なのと Promise.all が息してるってことで省きます。(そのうち追加するかも
配列で使えたスプレッド構文がオブジェクトでも使えるようになったよ
const {a, b, ...c} = {a: 1, b: 2, c: 3, d: 4} console.log(a) console.log(b) console.log(c) // 1 // 2 // { c: 3, d: 4 }
Promise の最後の処理として finally を追加しておけば、非同期処理の後処理などに使えるよ
const data = {} const promise = new Promise(resolve => { setTimeout(()=>{ data.status = 'Success' resolve('success') }, 2000) }) promise .then( value => { console.log(value) console.log(data) } ) .catch( value => { console.log(value) // { status: 'Failed' } console.log(data) } ) .finally( () => { console.log('後処理') } ) // success // { status: 'Success' } // 後処理
以下の機能が追加されたよ
4は記事が肥大化しそうなので今(2020/12/08 23:30)のところ割愛(便利そうだけど)
?<name>Pattern でキャプチャーに名前をつけられるようになったよ。$1, $2 ともおさらば
const origin = `Barack Hussein Obama II is an American politician and attorney who served as the 44th president of the United States from 2009 to 2017.` const regex = /^.+ (?<name>Obama) (?<be>.+) (?<job>president) .+$/ const result = origin.replace(regex, "$<name> was $<job>") console.log(result) // Obama was president
s フラグの追加で .(ドット)が改行文字にもマッチするように
const origin = ` Barack Hussein Obama II is an American politician and attorney who served as the 44th president of the United States from 2009 to 2017.` const regex = /(?<term>2009.to.2017)/s console.log(origin.match(regex).groups.term) // 2009 // to // 2017
/(?<=prePattern)pattern/ で後読みマッチに対応
const regex2 = /(?<=44th).president/s console.log(regex2.test(origin)) // true