toString.call()和判断变量类型

1. toString.call()

  • 字符串: [object String]
  • 数字: [object Number]
  • 数组: [object Array]
  • 对象: [object Object]
  • 方法: [object Function]
  • null, undefined: [object Null], [object Undefined]
  • toString.call(new Date()): [object Date]

2. 判断类型:

var isArrayLike = function(collection) {
    var length = getLength(collection);
    return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
  };

  var isString = function(obj) {
    return toString.call(obj) === '[object String]';
  };

  var isArguments = function(obj) {
    return toString.call(obj) === '[object Arguments]';
  };

var isArray = nativeIsArray || function(obj) {
    return toString.call(obj) === '[object Array]';
  };

  // Is a given variable an object?
  var isObject = function(obj) {
    var type = typeof obj;
    return type === 'function' || type === 'object' && !!obj;
  };

  // Is a given value a boolean?
  var isBoolean = function(obj) {
    return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
  };

  // Is a given value equal to null?
  var isNull = function(obj) {
    return obj === null;
  };

  // Is a given variable undefined?
  var isUndefined = function(obj) {
    return obj === void 0;
  };

// Is a given array, string, or object empty?
  // An "empty" object has no enumerable own-properties.
 var isEmpty = function(objOrArray) {
    if (objOrArray == null) {
      return true;
    }
    if (isArrayLike(objOrArray) && (isArray(objOrArray) || isString(objOrArray) || isArguments(objOrArray))) {
      return objOrArray.length === 0;
    }
    return keys(objOrArray).length === 0;
  };

推荐阅读更多精彩内容