JavaScript 各种类型判断

变量

function User(){}
User.prototype.callName=function(){return 'zengwe'}
let num = 123;
let str = '123';
let bool = true;
let und = undefined;
let nul = null;
let obj = new User();
let obj2 = {};
let obj3 = Object.create({});
let arr = [12];
let reg = new RegExp('aaa');
let date = new Date();
let err = new Error('some error');

typeof

typeof操作符返回一个字符串,表示未经计算的操作数的类型

function TypeOf(value) {
  console.log(typeof value);
}
TypeOf(User); // function
TypeOf(getType); // function
TypeOf(num); // number
TypeOf(str); // boolean
TypeOf(bool); // undefined
TypeOf(und); // object
TypeOf(nul); // object
TypeOf(obj); // object
TypeOf(obj2); // object
TypeOf(obj3); // object
TypeOf(arr); // object
TypeOf(reg); // object
TypeOf(date); // object
TypeOf(err); // object

Object.prototype.toString.call()

判断原生引用类型

function getType(value) {
  console.log(Object.prototype.toString.call(value));
}
getType(User); // [object Function]
getType(getType); // [object Function]
getType(num); // [object Number]
getType(str); // [object String]
getType(bool); // [object Boolean]
getType(und); // [object Undefined]
getType(nul); // [object Null]
getType(obj); // [object Object]
getType(obj2); // [object Object]
getType(obj3); //[object Object]
getType(arr); // [object Array]
getType(reg); // [object RegExp]
getType(date); // [object Date]
getType(err); // [object Error]

instanceof

instanceof运算符用于测试构造函数的prototype属性是否出现在对象的原型链中的任何位置

function Student() { }
var studentA = new Student();
 
console.info(studentA instanceof Student);
function Person() { }  
Student.prototype = Object.create(Person); // true
Student.prototype.constructor = Student;
let personA = new Person();
console.info(studentA instanceof Student)  // false
console.info(studentA instanceof Person) // false
console.info(personA instanceof Student)  // false
console.info(personA instanceof Person) // true
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值