黑马程序员技术交流社区

标题: 判断数据类型的方法 [打印本页]

作者: 啦啦啦啦lll    时间: 2020-12-21 15:08
标题: 判断数据类型的方法
1.使用typeof来判断数据类型
console.log(
    typeof 123, //"number"
    typeof 'dsfsf', //"string"
    typeof false, //"boolean"
    typeof [1,2,3], //"object"
    typeof {a:1,b:2,c:3}, //"object"
    typeof function(){console.log('aaa');}, //"function"
    typeof undefined, //"undefined"
    typeof null, //"object"
);
2.使用instanceof,instanceof需要指定一个构造函数,或者说指定一个特定的类型,它用来判断这个构造函数的原型是否在给定对象的原型链上

console.log(
    123 instanceof Number, //false
    'dsfsf' instanceof String, //false
    false instanceof Boolean, //false
    [1,2,3] instanceof Array, //true
    {a:1,b:2,c:3} instanceof Object, //true
    function(){console.log('aaa');} instanceof Function, //true
    undefined instanceof Object, //false
    null instanceof Object, //false
)
3.constructor是prototype对象上的属性,指向构造函数。根据实例对象寻找属性的顺序,若实例对象上没有实例属性或方法时,就去原型链上寻找,因此,实例对象也是能使用constructor属性的
console.log(new Number(123).constructor)
可以看到它指向了Number的构造函数,因此,可以使用num.constructor==Number来判断一个变量是不是Number类型的。
var num  = 123;
var str  = 'abcdef';
var bool = true;
var arr  = [1, 2, 3, 4];
var json = {name:'wenzi', age:25};
var func = function(){ console.log('this is function'); }
var und  = undefined;
var nul  = null;
function Person(){
  
}
var tom = new Person();

// undefined和null没有constructor属性
console.log(
    tom.constructor==Person,
    num.constructor==Number,
    str.constructor==String,
    bool.constructor==Boolean,
    arr.constructor==Array,
    func.constructor==Function,
);
//所有结果均为true
除了undefined和null之外,其他类型都可以通过constructor属性来判断类型。





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2