3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

配列代入時に条件付き要素を追加しない方法

3
Last updated at Posted at 2026-05-31

次のように三項演算子で配列代入時、要素の追加有無制御しようにすると、false のときでも配列に要素が追加されてしまう。

function sample(bool: boolean) {
  const tmp = [
    'item1',
    bool ? 'item?' : null, // falsyの場合、nullが要素として追加されてしまう
    'item2'
  ];

  console.log(tmp.length); // boolの真偽に関わらず、3になる
}

boolfalse の場合、配列は ['item1', null, 'item2'] になり、要素数は 3 のままです。

スプレット構文と組み合わせることで、要素を追加せずに済む。

function sample(bool: boolean) {
  const tmp = [
    'item1',
    ...(bool ? ['item?'] : []),
    'item2'
  ];

  console.log(tmp.length); // boolがfalsyな場合、2になる
}

この書き方なら、boolfalse のときには ['item1', 'item2'] となり、不要な null 要素が含まれない。

3
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
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?