2020.12.09
ざっくり ECMAScript 2018
ざっくりと ES2018 のおさらいをしたい人向け。オカタい説明は mdn さんあたりにおまかせするとして、ゆるっとざっくり気楽にサクッとコードベースでおさらい。ES2018 は for-await-ofの追加、正規表現周りの調整、Promiseにfinallyの追加、テンプレートリテラルが見直されたよ。
環境構築
- MacOS High Sierra
- ふる〜い MBP 使ってます
- nvm, ndenv, nodebrew のどれでもいいので node が動く環境を用意
- VSCode 使ってます。拡張はお好みで。
- node.js のバージョンは v14.7.0
- 適当なディレクトリを掘って、index.js を用意しています (ファイル名はお好みで)
- 動作確認は $ node index.js って叩いてます
最小限で動かすだけならこれだけでおっけいです。ここらへんの準備も面倒ならば codepen だの JSFiddle だの REPL だのを使ってもおk
es2018
es2018 は以下のような機能が追加されている(参考 Wikipedia ECMAScript)
オブジェクトに対するスプレッド構文、非同期イテレーション、Promise.prototype.finally、正規表現への機能追加
非同期イテレーションである for-await-of に関しては、今日の時点で ESLint 非推奨 なのと Promise.all が息してるってことで省きます。(そのうち追加するかも
オブジェクトに対するスプレッド構文
配列で使えたスプレッド構文がオブジェクトでも使えるようになったよ
1 2 3 4 5 6 7 8 9 |
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.prototype.finally
Promise の最後の処理として finally を追加しておけば、非同期処理の後処理などに使えるよ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
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' } // 後処理 |
正規表現の新機能
以下の機能が追加されたよ
- キャプチャに名前をつけられるようになった
- sオプションを追加することで . (ドット)を改行文字と一致するように
- 後読みマッチ(Lookbehind)
- Unicode文字が持つプロパティにマッチさせられるようになった
4は記事が肥大化しそうなので今(2020/12/08 23:30)のところ割愛(便利そうだけど)
1. Named Capture Groups
?<name>Pattern でキャプチャーに名前をつけられるようになったよ。$1, $2 ともおさらば
1 2 3 4 5 6 7 |
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 |
2. dotAll flag
s フラグの追加で .(ドット)が改行文字にもマッチするように
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
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 |
3. Lookbehind Assertions
/(?<=prePattern)pattern/ で後読みマッチに対応
1 2 3 4 |
const regex2 = /(?<=44th).president/s console.log(regex2.test(origin)) // true |