lodashのさまざまな真偽値判定
lodashのisXXXXを使ったりするのですが、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({}));
}