現代的JavaScriptおれおれアドベントカレンダー2017 – 15日目
概要
オブジェクトとかでまとまってもらえる情報を、最初からバラバラにしちゃうやつです。配列でも使えます。
1 2 3 4 5 6 | const arr = [ 'https:' , 'ginpen.com' , '/about' /]; const [protocol, host, path] = arr; console.log(protocol); // => "https:" console.log(host); // => "ginpen.com" console.log(path); // => "/about/" |
String#match()
で猛威を振るいそう。(?)
使い方
左辺にしかく括弧 [
… ]
で括って、初期化なり代入なりする変数の名前を書きます。
1 2 3 4 5 | const arr = [11, 22]; const [a, b] = arr; console.log(a); // => 11 console.log(b); // => 22 |
順序左側の順序と右側の順序が一致します。
いらない値を飛ばす
カンマ ,
だけ書いて変数名を省略すると、そこの位置の値を飛ばします。
1 2 3 4 5 | const arr = [11, 22, 33]; const [a, , b] = arr; console.log(a); // => 11 console.log(b); // => 33 |
残りの値をまとめる
...
を使って「残り」を全てひとつの新しい配列に突っ込むことができます。
1 2 3 4 5 | const arr = [11, 22, 33, 44]; const [first, ...rest] = arr; console.log(first); // => 11 console.log(rest); // => [22, 33, 44] |
この ...
は関数の仮引数でも使えます。別稿参照。
初期値
オブジェクトのやつと同様、 =
で初期値を設定できます。
1 2 3 4 5 6 7 | const arr = [-1, undefined, -3]; const [a = 11, b = 22, c = 33, d = 44] = arr; console.log(a); // => -1 console.log(b); // => 22 console.log(c); // => -2 console.log(d); // => 44 |
入れ子
これもオブジェクトのやつと同様。
1 2 3 4 5 | consr arrrr = [ '1' , [ '2-1' , [ '2-2-1' ]], 3]; const [a, [, [x]], c] = arrrr; console.log(a); // => '1' console.log(x); // => '2-2-1' |
もちろんオブジェクトと組み合わせて使うこともできます。
1 2 3 4 5 | const data = { names: [ 'Martin' , 'Luther' , 'King' ] }; const { names: [first, , family] } = data console.log(first); // => 'Martin' console.log(family); // => 'King' |
String#match()
と組み合わせる
諸々便利かなと思います。
例えば日付を分解する。
1 2 3 4 5 6 7 | const rxDate = /(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)/; const sDate = '2017-12-15 10:05:00' ; const [, year, month, date, hours, minutes, seconds] = sDate.match(rxDate); console.log(year); // => "2017" console.log(hours); // => "10" |
結果の先頭には条件に合致した全体が入ってくるけど、今回いらないので、値を捨てます。
変数の中身を入れ替える
MDNに載ってたけどあんまり使わない気がする。
1 2 3 4 5 6 | let a = 'A' ; let b = 'B' ; [a, b] = [b, a]; console.log(a); // => "B" console.log(b); // => "A" |
んー何かのアルゴリズムとかでこういうことしたっけかな。
引数とか?の先頭とそれ以外を分ける
例はNode.jsの方ですけども、なんかこういうのすることもあるかもしれない。
1 2 3 4 5 6 7 8 9 | const { spawn } = require( 'child_process' ); const input = 'ls -a -l /var/log' ; const [command, ...args] = input.split( ' ' ); spawn(command, args) .stdout.on( 'data' , (data) => { console.log(data.toString()); }); |
その他
省略のカンマ ,
仕様書では “elision” と呼称されているようです。
主な意味: (母音・音節などの)省略
参考
- ECMAScript® 2017 Language Specification
- 12.15.5 Destructuring Assignment … 最初の初期化
- 12.15.5.2 Runtime Semantics: DestructuringAssignmentEvaluation … 評価の様子(長くて読めてない……)
- 13.3.3 Destructuring Binding Patterns … 後から代入
- 14.1 Function Definitions
- 分割代入 – JavaScript | MDN
- 分割代入、画期的な機能。(現代的JavaScriptおれおれアドベントカレンダー2017 – 14日目) … オブジェクトのほう