Heading for the future

JS类型判断

typeof

typeof 123;   // number
typeof 'test';  // string
typeof true;  // boolean
typeof [1,2,3]; // object
typeof {name:'wenzi', age:25}; // object
typeof function(){ console.log('this is function'); }; // function
typeof undefined; // undefined
typeof null; // object
typeof new Date(); // object
typeof /^[a-zA-Z]{5,20}$/; // object
typeof new Error(); // object

注意⚠️: typeof null为object,typeof function (){}为function.在使用 typeof 运算符时采用引用类型存储值会出现一个问题,无论引用的是什么类型的对象,它都返回 “object”

instanceof

instanceof 是用来判断 A 是否为 B 的实例,表达式为:A instanceof B,如果 A 是 B 的实例,则返回 true,否则返回 false。 在这里需要特别注意的是:instanceof 检测的是原型

class Person{
  constructor(name){
        this.name= name;  
    }
}
let p = new Person('张三')
 console.log(p instanceof  Person) //ture

注意⚠️:

  • 对于number,string,boolean这三种类型,只有通过构造函数定义才能检测出来
  • 处理不了null 和 undefined
1 instanceof Number // false
'str' instanceof String // false
true instanceof Boolean // false

new Number(1) instanceof Number // true
new String('str') instanceof String // true
new Boolean(true) instanceof Boolean // true

constructor

constructor是原型对象的属性,他指向构造函数。

new Number(1).constructor === Number // true
new String(1).constructor === String // true
true.constructor === Boolean // true
new Function().constructor === Function // true
new Date().constructor === Data // true
new Error().constructor === Error // true
[].constructor === Array // true
document.constructor === HTMLDocument // true
window.constructor === Window // true

或者使用constructor.name
栗子🌰:
new Number(1).constructor.name === 'Number' // true

注意⚠️:

  • constructor所指向的的构造函数是可以被修改的
  • null 和 undefined 无constructor,这种方法判断不了

Object.prototype.toString.call()

toString() 是 Object 的原型方法,调用该方法,默认返回当前对象的 [[Class]] 。这是一个内部属性,其格式为 [object Xxx] ,其中 Xxx 就是对象的类型。对于 Object 对象,直接调用 toString()  就能返回 [object Object] 。而对于其他对象,则需要通过 call / apply 来调用才能返回正确的类型信息。

Object.prototype.toString.call('') ;   // [object String]
Object.prototype.toString.call(1) ;    // [object Number]
Object.prototype.toString.call(true) ; // [object Boolean]
Object.prototype.toString.call(Symbol()); //[object Symbol]
Object.prototype.toString.call(undefined) ; // [object Undefined]
Object.prototype.toString.call(null) ; // [object Null]
Object.prototype.toString.call(new Function()) ; // [object Function]
Object.prototype.toString.call(new Date()) ; // [object Date]
Object.prototype.toString.call([]) ; // [object Array]
Object.prototype.toString.call(new RegExp()) ; // [object RegExp]
Object.prototype.toString.call(new Error()) ; // [object Error]
Object.prototype.toString.call(document) ; // [object HTMLDocument]
Object.prototype.toString.call(window) ; //[object global] window 是全局对象 global 的引用

参考自

https://www.cnblogs.com/yadiblogs/p/10750775.html

https://www.jb51.net/article/70824.htm

https://blog.csdn.net/u010998803/article/details/80732942

https://www.cnblogs.com/liujiekun/p/10870788.html

posted @ 2020-09-07 08:39  一只菜鸟攻城狮啊  阅读(227)  评论(0编辑  收藏  举报