javascript 配列が空であるかを判定する

javascript 配列が空であるかを判定する

javascriptで、配列が空であるかを判定するサンプルコードを掲載してます。配列のサイズを「length」で調べて0であれば空、0以外であればから出ないと判定します。ブラウザはchromeを使用しています。

環境

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

配列が空であるかを判定

配列が空であるかを判定するには、サイズを調べることのできる「length」を使用します。

'use strict';

const arr = []

// 配列が空であれば「length」は「0」が返ります
if (arr.length === 0) {

  console.log('空です')

}else{

  console.log('空でない')

}

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

ただし「length」は値を指定すると、値が変わってしまいます。

const arr = []

arr.length = 5;

// 配列が空であれば「length」は「0」が返ります
if (arr.length === 0) {

  console.log('空です')

}else{

  console.log('空でない')

}

実行結果

また、「0」が「true」扱いとなるので、以下のように記述することも可能です。

if (!arr.length) {
  console.log('空です')
}else{
  console.log('空でない')
}

三項演算子を使用して、簡潔に記述することもできます。

!arr.length ? console.log('空です') : console.log('空でない')

空の配列小ネタ

ちなみに、空の配列「==」で比較とおかしな結果になることが多いので注意してください。

console.log( [] == '' ); // true
console.log( [] == 0  ); // true
console.log( [''] == '' ); // true
console.log( [0] == 0 ); // true
console.log( [''] == 0 ); // true

console.log( [0] == '' ); // false

サンプルコード

以下は、
「実行」ボタンをクリックして、空の配列を用意して判定した結果を表示するサンプルコードとなります。

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

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

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
</head>

<script>

  const arr = []

  const hoge = () => {

    fuga.textContent = !arr.length ? '空です' : '空でない'

  }

  window.onload = () => {

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

  }

</script>

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

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

      <h1 class="font-semibold text-gray-500 text-lg mr-auto">実行結果</h1>
      <h1 id="fuga" class="font-semibold text-gray-500 text-lg mr-auto"></h1>      

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

    </div>

  </div>
</body>

</html>

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

また、javascript部はwindowを省略して記述することも可能です。

onload = () => {

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

}