0
点赞
收藏
分享

微信扫一扫

js判断变量类型:typeof、instanceof、constructor、Object.prototype.toString.call()的区别

倪雅各 2022-03-11 阅读 97
前端

定义一组变量

let num = 123;
let str = 'abcd';
let bool = true;
let obj = { a: '1' };
let arr = [1, 2, 3];
let fun = function () {};
let und = undefined;
let nul = null;
let date = new Date();
let reg = new RegExp();
let err = new Error();

1.使用typeof检测

// 简单数据类型 如数字、字符串、布尔、undefined、函数可以用typeof检测出来
// 复杂数据类型对象、数组、日期、正则、null 得到的都是'object'
console.log(
  typeof num, // number
  typeof str, // string
  typeof bool, // boolean
  typeof obj, // object
  typeof arr, // object
  typeof nul, // object
  typeof date, // object
  typeof reg, // object
  typeof err, // object
  typeof fun, // function
  typeof und // undefined
);

2.使用instanceof检测

instanceof是通过__proto__来检测当前变量是否属于某个构造函数的

只有被new出来的才属于, null和undefined没有构造函数

console.log(
  num instanceof Number, // false
  str instanceof String, // false
  bool instanceof Boolean, // false
  obj instanceof Object, // true
  arr instanceof Array, // true
  nul instanceof Object, // false
  date instanceof Object, // true
  reg instanceof Object, // true
  err instanceof Object, // true
  fun instanceof Function, // true
  und instanceof Object // false
);

3.使用constructor检测

console.log(
  num.constructor, // Number
  str.constructor, // String
  bool.constructor, // Boolean
  obj.constructor, // Object
  arr.constructor, // Array
  date.constructor, // Date
  reg.constructor, // RegExp
  err.constructor, // Error
  fun.constructor // Function
  // nul.constructor, // null 没有constructor
  // und.constructor // undefined 没有constructor
);

4.Object.prototype.toString.call()

console.log(
  Object.prototype.toString.call(num), // [object Number]
  Object.prototype.toString.call(str), // [object String]
  Object.prototype.toString.call(bool), // [object Boolean]
  Object.prototype.toString.call(obj), // [object Object]
  Object.prototype.toString.call(arr), // [object Array]
  Object.prototype.toString.call(date), // [object Date]
  Object.prototype.toString.call(reg), // [object RegExp]
  Object.prototype.toString.call(err), // [object Error]
  Object.prototype.toString.call(fun), // [object Function]
  Object.prototype.toString.call(nul), // [object Null]
  Object.prototype.toString.call(und) // [object Undefined]
);
举报

相关推荐

0 条评论