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 5 years have passed since last update.

[js]PHPで言うところのempty関数を実装してみた

Last updated at Posted at 2018-07-09

はじめに

PHPの empty 関数、便利じゃないですか?私はよく使ってます。
jsでも同じような関数があればいいのですが、連想配列の空判定が色々と面倒みたいで、配列・連想配列・文字列・数値なんかを考慮せずに空かどうか判定したかったので自作してみました。

ちなみに

PHPの empty 関数は次のような挙動です。
"0" の扱いとは。

php_empty
 ''     => true
 ""     => true
 0      => true
"0"     => true  // 注意
 0.0    => true
"0.0"   => false
 null   => true
"null"  => false
 true   => false
"true"  => false
 false  => true
"false" => false
[]      => true
[[]]    => false

コード&動作確認

概要

以下からどうぞ。
なお、PHPでは "0"empty 扱いとなりますが、本コードでは not empty とするようにしています。
判定甘くしてあげればPHPと同じ挙動になるかと。その是非は別にして。

js_empty
''          => true
""          => true
 0          => true
"0"         => false  // 注意:PHPと挙動を変えている
 0.0        => true
"0.0"       => false
 null       => true
"null"      => false
 true       => false
"true"      => false
 false      => true
"false"     => false
 undefined  => true
"undefined" => false
[]          => true
[[]]        => false
{}          => true
[{}]        => false

使い方

test 関数内の配列に左から [テストしたい値, 画面に表示される文字, 期待値] で入れてあげればOKです。
挙動チェックついでにアサーションしてくれるすごいやつだ!

コード

See the Pen js-isEmpty by tosite (@tosite) on CodePen.

終わりに

もしもっといいやり方あったら教えてください。

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