Contents
JavaScriptの分かりづらい構文
JavaScriptの構文で分かりずらかったトコ、かつ、インターネットで調べるのが困難であった構文を上げていきます。
スプレッド構文(「…」ドット3つのやつ)
配列ライクなオブジェクト(正確には for of で展開できるオブジェクト)を個々の値に展開することができます。
以下のように使える
1 2 3 4 5 6 7 |
function sum(x, y, z) { return x + y + z; } const numbers = [1, 2, 3]; console.log(sum(...numbers)); //6 |
分割代入
オブジェクトの分割代入
オブジェクトのキーを指定して、別の変数に入れる。
1 2 3 4 5 6 7 8 |
const user = { name: 'test user', age: 18, email: 'example@example.com' } const { email } = user console.log(email) // -> 'example@example.com' |
スプレッド構文+分割代入
スプレッド構文は左辺にも持ってこれる
1 2 3 4 5 6 7 8 9 10 |
const user = { name: 'test user', age: 18, email: 'example@example.com' } const { email, ...other } = user console.log(email) // -> 'example@example.com' console.log(other.name); // -> 'test user' console.log(other.age); // -> 18 |
アロー関数
アロー関数は、functionの代わりに矢印を使った無名関数の定義記法。
以下の2つは同じ意味。
1 2 3 4 5 6 7 |
(a, b) => { return a + b } function(a, b) { return a + b } |