JS 常用方法

212 阅读1分钟

判断是否为数组,对象,字符串,无值,内容为空,null

  isArray: function (o) {
    return Object.prototype.toString.call(o) === '[object Array]';
  },
  isObject: function (o) {
    return Object.prototype.toString.call(o) === '[object Object]';
  },
  isString: function (o) {
    return Object.prototype.toString.call(o) === '[object String]';
  },
  isBlank: function (varValue) {
    if (varValue !== null && varValue !== undefined && varValue !== '' && varValue !== 'null') {
      return false;
    }
    return true;
  },
  isEmpty: function (obj) {
    if (obj == null) return true;
    if (obj.length > 0) return false;
    if (obj.length === 0) return true;
    if(!Object.keys(obj).length) return true;
    for (let key in obj) {
      if (hasOwnProperty.call(obj, key)) return false;
    }
    return true;
  },
  isNull: function (obj) {
    return obj === null || typeof(obj) === 'undefined'
  },

判断变量是否被赋值

if (typeof y === 'undefined') {
  y = 'World';
}

判断设备是电脑还是手机

  isPc () {
    /**
     * To determine whether it is pc || mobile
     * @param flag true则pc,false则mobile
     */
    let userAgentInfo = navigator.userAgent;
    let Agents = ["Android", "iPhone", "webOS", "BlackBerry","SymbianOS", "Windows Phone","iPad", "iPod"];
    let flag = true;
    for (let v = 0; v < Agents.length; v++) {
      if (userAgentInfo.indexOf(Agents[v]) > 0) {
        flag = false;
        break;
      }
    }
    return flag;
  },

去除字符串两端的空白字符(或者只有左边、右边、全部)

  • 写在一个方法中
  trim (str, type = 'both') {
    switch (type) {
      case 'both':
        return str.replace(/(^\s*)|(\s*$)/g, "");
        break;
      case 'left':
        return str.replace(/(^\s*)/g, "");
        break;
      case 'right':
        return str.replace(/(\s*$)/g, "");
      case 'all':
        return str.replace(/\s+/g, "");
    }
  },
  • 分开写
  trim (str) {
    return str.replace(/(^\s*)|(\s*$)/g, "");
  }
  trimLeft (str) {
    return str.replace(/(^\s*)/g, "");
  }
  trimRight (str) {
    return str.replace(/(\s*$)/g, "");
  }
  trimAll (str) {
    return str.replace(/\s+/g, "");
  }

jquery 有 $.trim( str ) 方法,用于去除字符串两端的空白字符。