10
6

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

lodashの真偽値判定まとめ

Posted at

lodashのさまざまな真偽値判定

lodashisXXXXを使ったりするのですが、undefinedのときtrueだっけ・・・?
と迷うことが多々あったのでまとめてみました。

検証バージョンは4.17.14です。

引数 引数(コード) _.isEmpty() _.isNaN() _.isNil() _.isNull() _.isUndefined()
空文字 '' true false false false false
半角スペース ' ' false false false false false
NaN NaN true true false false false
null null true false true true false
undefined undefined true false true false true
真偽値 true true false false false false
数字 0 true false false false false
文字 'hoge' false false false false false
配列 [0,1,2] false false false false false
空配列 [] true false false false false
オブジェクト {hoge:'hoge'} false false false false false
空のオブジェクト {} true false false false false

isEmpty使用するときは要注意ですね。。

おまけ

以下で確認しました。

this.checkFuncReturnValue('isEmpty', hoge => _.isEmpty(hoge));
this.checkFuncReturnValue('isNaN', hoge => _.isNaN(hoge));
this.checkFuncReturnValue('isNil', hoge => _.isNil(hoge));
this.checkFuncReturnValue('isNull', hoge => _.isNull(hoge));
this.checkFuncReturnValue('isUndefined', hoge => _.isUndefined(hoge));
checkFuncReturnValue(funcName, func) {
  console.log(funcName);
  console.log(' blank =>' + func(''));
  console.log(' halfSpace =>' + _.isEmpty(' '));
  console.log(' fullSpace =>' + _.isEmpty(' '));
  console.log(' NaN =>' + func(NaN));
  console.log(' null =>' + func(null));
  console.log(' undefined =>' + func(undefined));
  console.log(' true =>' + func(true));
  console.log(' number =>' + func(0));
  console.log(' string =>' + func('hoge'));
  console.log(' array =>' + func([0, 1, 2]));
  console.log(' emptyArray =>' + func([]));
  console.log(' object =>' + func({ hoge: 'hoge' }));
  console.log(' emptyObject =>' + func({}));
}
10
6
2

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
10
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?