js判断类型

1)instanceof运算符判断类型

function Aaa(){ //父类
          this.name = '小明'
        }
        let a = new Aaa()
        let str = new String('asd');
        let str2 = 'asdf';
        let obj = {name:'小明'};
        let arr = [];
        let bool = new Boolean(false);
        let bool2 = true;
        let num = new Number(456);
        let num2 = 456;
        console.log(a instanceof Object) // true
        console.log(a instanceof Aaa) // true
        console.log(str instanceof String) // true
        console.log(str instanceof Object) // true
        console.log(str2 instanceof String) // false
        console.log(str2 instanceof Object) // false
        console.log(obj instanceof Object) // true
        console.log(arr instanceof Array) // true
        console.log(arr instanceof Object) // true
        console.log(bool instanceof Boolean) // true
        console.log(bool instanceof Object) // true
        console.log(bool2 instanceof Boolean) // false
        console.log(bool2 instanceof Object) // false
        console.log(num instanceof Number) // true
        console.log(num instanceof Object) // true
        console.log(num2 instanceof Number) // false
        console.log(num2 instanceof Object) // false

2)利用Object原型上的toString方法判断,最准确

字符串 [object String]
构造函数 [object Object]
对象 [object Object]
数组 [object Array]
布尔值 [object Boolean]
数字 [object Number]

function Aaa(){ //父类
          this.name = '小明'
        }
        let a = new Aaa()
        let str = new String('asd');
        let str2 = 'asdf';
        let obj = {name:'小明'};
        let arr = [];
        let bool = new Boolean(false);
        let bool2 = true;
        let num = new Number(456);
        let num2 = 456;
        console.log(Object.prototype.toString.call(a)) //'[object Object]'
        console.log(Object.prototype.toString.call(str)) //'[object String]'
        console.log(Object.prototype.toString.call(str2)) // '[object String]'
        console.log(Object.prototype.toString.call(obj))// '[object Object]'
        console.log(Object.prototype.toString.call(arr)) // '[object Array]'
        console.log(Object.prototype.toString.call(bool)) // '[object Boolean]'
        console.log(Object.prototype.toString.call(bool2)) //'[object Boolean]'
        console.log(Object.prototype.toString.call(num)) //'[object Number]'
        console.log(Object.prototype.toString.call(num2)) //'[object Number]'
        console.log(Object.prototype.toString.call(num2) == '[object Number]')  //true
            

你可能感兴趣的:(js判断类型)