2
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?

More than 1 year has passed since last update.

if文でもin演算子が使える JavaScript

Last updated at Posted at 2022-02-23

if文でもin演算子が使用できます。
プロパティがオブジェクトにある場合にtrueを返します。

if ('property' in obj) {
    // 処理
}

例(修正前)

const card = { type: 'mtg', color: 'white' };
console.log('type' in card);  // 出力:true

delete card.color;
if ('color' in card === false) {
	card.color = 'black';
}
console.log(card.color);  // 出力:black

コメントでご指摘をいただき修正した例
ifの条件でfalseと比較せずに、否定演算子を使う

const card = { type: 'mtg', color: 'white' };
console.log('type' in card);  // 出力:true

delete card.color;
if (!('color' in card)) {
	card.color = 'black';
}
console.log(card.color);  // 出力:black
2
0
3

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
2
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?