JS类型判断全总结

为了不死在笔试,为秋招作的准备
分为两个部分,一部分讲方法,一部分判断实例
1.Array.prototype 是数组,Object.prototype是对象,Function.prototype是函数

设要判断的变量为variable,要判断的类型X
一、方法:
- 1.typeof variable === X
- 2.variable instanceof X
- 3.variable.constructor === X
- 4.Object.prototype.toString.call(variable) === X

(1)typeof

判断基本类型和Object时
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

值得注意的examples:

typeof Math.LN2 === 'number';
typeof Infinity === 'number';
typeof NaN === 'number'; 

typeof '1' === 'string';
typeof (typeof 1) === 'string';

typeof [1, 2, 4] === 'object';
//new 开头的都是'object'
typeof new Date() === 'object';
typeof new Boolean(true) === 'object'; 
typeof new Number(1) === 'object'; 
typeof new String('abc') === 'object';

typeof class C {} === 'function';
typeof Math.sin === 'function';
//几个特列
typeof undefined === 'undefined';
typeof document.all === 'undefined';
typeof null === 'object';
typeof /regularexpression/ === 'object';

(2)instanceof

功能:Checks the current object and returns true if the object
is of the specified object type.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof
https://stackoverflow.com/questions/2449254/what-is-the-instanceof-operator-in-javascript

值得注意的examples:

var color1 = new String("green");
color1 instanceof String; // returns true
var color2 = "coral"; //no type specified
color2 instanceof String; // returns false (color2 is not a String object)

// So what instanceof does is it checks the object to see if it is of the type specified
var c = new Customer();
c instanceof Customer; //Returns true 
c instanceof String; //Returns false 

(3)variable.constructor === X
>

(4)

1.variable.constructor === Array
2.variable instanceof Array
3.Array.isArray(variable)
4.Object.prototype.toString.call(variable) === ‘[object Array]’;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值