LoginSignup
0
0

More than 5 years have passed since last update.

オブジェクトの分割代入の実験:「分割代入する変数の順番入れ替え」「既定値が使われるケース」

Last updated at Posted at 2017-05-02

ちょっと気になったところを実験

'use strict'
// 1
{
  // オブジェクト
  const a = {
    b: 1,
    c: 2,
    d: 3
  };

  {

    // 1-1 代入する値の順番を入れ替えるどうなる?
    const { c, d, b } = a;
    console.log('1-1:', b, c, d);
    // 1 2 3 
    // ちゃんとプロパティ名と一致する変数に値が代入される
  }

  // 1-2じゃこれは?
  {
    const { b: c, c: d, d: b } = a;
    console.log('1-2:', b, c, d);
    // 3 1 2 
  }
}

// 2
{
  const a = {
    b: 1,
    c: 2
  }
  // 関数の引数としての分割代入
  function f({ b, c, d = 3 }, sectionNo) {
    console.log(`${sectionNo}:`, b, c, d);
  }
  f(a, '2-1');
  // 1 2 3
  // 未定義のプロパティは既定値が代入される

  a.d = undefined;
  f(a, '2-2');
  // 1 2 3
  // undefinedだと既定値が代入される

  a.d = null;
  f(a, '2-3');
  // 1 2 null
  // nullだと既定値が代入されない。この挙動は普通の変数の既定値と同じ。
}

以上

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0