LoginSignup
0
0

More than 3 years have passed since last update.

JavaScriptで空の配列を判別する方法

Last updated at Posted at 2020-05-14

個人的にすごく詰まったので、メモとして残しておく。

JavaScriptでは条件式の中に比較演算子がない場合、要素によって真偽判定が行われるが、文字列などとは異なり、配列では空の場合でもTrueと判定されてしまう。

script
const name_string = ""  //空の文字列
console.log(Boolean(name_string))  //False

const name_list_1 = []  //空の配列
const name_list_2 = [1] //要素のある配列

//配列の要素の有無にかかわらずTrueを返してしまう
console.log(Boolean(name_list_1)) // True
console.log(Boolean(name_list_2)) // True

そのため、配列に要素が入っているか判定する場合には、配列の長さを求める.lengthを用いて行う。

script
const name_list_1 = []  //空の配列
const name_list_2 = [1] //要素のある配列

//配列が空のときFalseを返すようになった
console.log(Boolean(name_list_1.length)) // False
console.log(Boolean(name_list_2.length)) // True

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