js类型判断

js类型判断

typeof

typeof 返回值有七种可能: “number,” “string,” “boolean,” “object,” “function,” , “undefined,”symbol”

局限性:对于Array,Null等特殊对象使用typeof一律返回object。

// Numbers
typeof 37 === 'number';
typeof Math.LN2 === 'number';
typeof Infinity === 'number';
typeof NaN === 'number'; 
typeof Number(1) === 'number'; 
typeof Number() === 'number';

// Strings
typeof "bla" === 'string';
typeof (typeof 1) === 'string'; 
typeof String("abc") === 'string'; 

// Booleans
typeof true === 'boolean';
typeof Boolean(true) === 'boolean'; 

// Symbols
typeof Symbol() === 'symbol'
typeof Symbol('foo') === 'symbol'
typeof Symbol.iterator === 'symbol'

// Undefined
typeof undefined === 'undefined';
typeof undeclaredVariable === 'undefined'; 

// Objects
typeof {a:1} === 'object';
typeof [1, 2, 4] === 'object';
typeof new Date() === 'object';
typeof /s/ === 'object';
typeof Math === 'object'
typeof new Boolean(true) === 'object'; 
typeof new Number(1) === 'object'; 
typeof new String("abc") === 'object';
typeof null === 'object';

// Functions
typeof function(){} === 'function';
typeof class C {} === 'function';
typeof Math.sin === 'function';
typeof Number === 'function';
instanceof
[1] instanceof Array  //true
function a(){};   a instanceof Function   //大写F
Object.prototype.toString.call
Object.prototype.toString.call([1]) === '[object Array]'  //true
Object.prototype.toString.call(1) === '[object Number]'  //true
Object.prototype.toString.call('') === '[object String]'  //true
Object.prototype.toString.call(true) === '[object Boolean]'  //true
Object.prototype.toString.call({}) === '[object Object]'  //true
Object.prototype.toString.call(Symbol()) === '[object Symbol]'  //true
Object.prototype.toString.call(function(){}) === '[object Function]'  //true
提供的方法
Array.isArray([1])  //true
isNaN(NaN)  //ture
null === null  //true
null == undefined  //true   二者和0或false比较都为false
0 == false //  true
类的继承判断

Object.getPrototypeOf方法可以用来从子类上获取父类。

Object.getPrototypeOf(ChildrPoint) === Point  // true

因此,可以使用这个方法判断,一个类是否继承了另一个类。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值