小程序或js,判斷變量(Undefined String Array Object)是否爲空

關鍵代碼

function isBlank(str){
  if (Object.prototype.toString.call(str) ==='[object Undefined]'){//空
    return true
  } else if (
    Object.prototype.toString.call(str) === '[object String]' || 
    Object.prototype.toString.call(str) === '[object Array]') { //字條串或數組
    return str.length==0?true:false
  } else if (Object.prototype.toString.call(str) === '[object Object]') {
    return JSON.stringify(str)=='{}'?true:false
  }else{
    return true
  }

}

測試結果
陳科肇


小程序使用方法

utils.js文件


const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}


/**
 * 用於判斷空,Undefined String Array Object
 */
function isBlank(str){
  if (Object.prototype.toString.call(str) ==='[object Undefined]'){//空
    return true
  } else if (
    Object.prototype.toString.call(str) === '[object String]' || 
    Object.prototype.toString.call(str) === '[object Array]') { //字條串或數組
    return str.length==0?true:false
  } else if (Object.prototype.toString.call(str) === '[object Object]') {
    return JSON.stringify(str)=='{}'?true:false
  }else{
    return true
  }

}


/**
 * 導出
 */
module.exports = {
    formatTime: formatTime,
    String:{
      isBlank: isBlank
    }
}

其它js文件使用

import { String } from '../../utils/util.js';
var xx = '';
if( String.isBlank(xx))
    //xx is blank
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章