javascript inを使用してオブジェクトに指定したプロパティが存在するか判定する

javascript inを使用してオブジェクトに指定したプロパティが存在するか判定する

javascriptで、inを使用してオブジェクトに指定したプロパティが存在するか判定するサンプルコードを掲載してます。ブラウザはchromeを使用しています。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 108.0.5359.99

inを使用してオブジェクトに指定したプロパティが存在するか判定

判定するには、以下のよう「in」を使用します。

'プロパティ名' in 変数

実際に「in」を使用して判定してみます。

'use strict'

const human = {
  name:'mebee', 
  age:30,
  tel:123456789
};

console.log(
  ('name' in human) // true
);

console.log(
  ('weight' in human) // false
);

サンプルコード

以下は、
「実行」ボタンをクリックした際に、オブジェクトに指定したプロパティが存在するかをinで判定した結果を表示するサンプルコードとなります。

※cssには「tailwind」を使用して、アロー関数で関数は定義してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.tailwindcss.com"></script>
</head>

<script>

  const hoge = () => {

    const human = {
      name: 'mebee',
      age: 30,
      tel: 123456789
    };

    const val = txt.value;

    foo.innerHTML = val in human;

  }

  window.onload = () => {

    btn.onclick = () => { hoge() };

  }

</script>

<body>
  <div class="container mx-auto my-56 w-64 px-4">

    <div id="sample" class="flex flex-col justify-center">

      <h1 class="font-semibold text-amber-500 text-lg mr-auto">判定結果</h1>
      <p id="foo" class="font-semibold text-lg mr-auto"></p>

      <input class="mb-2 shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="txt" type="text">

      <button id="btn"
        class="mb-2 md:mb-0 bg-transparent hover:bg-emerald-500 text-emerald-700 font-semibold hover:text-white py-2 px-4 border border-emerald-500 hover:border-transparent rounded">
        実行
      </button>

    </div>

  </div>
</body>

</html>

実行結果を確認すると、判定されていることが確認できます。