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

JavaScriptの便利部品

Posted at

空文字確認

引数で渡されたオブジェクトが空文字だったらTRUEを返す部品

  • 空文字の条件
  • Null
  • Undefined
  • 長さ0のString
  • 長さ0のArray

isBlank = function(chkObj) {
  if (chkObj == undefined || chkObj == null) {
    return true;
  }

  if (typeof chkObj == "boolean") {
    return !chkObj;
  } else if (typeof chkObj == "number") {
    return false;
  } else if (typeof chkObj == "string") {
    return (chkObj.length == 0) ? true : false;
  } else if (Array.isArray(chkObj)) {
    return (chkObj.length == 0) ? true : false;
  } else {
    return false
  }
}

使い方

if文の中で真偽(空文字かどうか)判定をして、空文字で無ければその後の処理を行う
等の使い方です。

// 例1 
let unKnownVal = "test";
if (!isBlank(unKnownVal)) {
  // 空文字で無ければコンソールに出力
  console.log(unKnownVal);
}

// 例2
let unKnownVal = "";
if(isBlank(unKnownVal)){
  // 空文字であればコンソールに出力
  console.log(unKnownVal);
}
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?