JavaScript类型识别

类型系统

搬运自个人博客,原址JavaScript类型识别
javascript 类型系统可以分为标准类型和对象类型,进一步标准类型又可以分为原始类型和引用类型,而对象类型又可以分为内置对象类型、普通对象类型、自定义对象类型。

js类型系统

类型转化表

ValueBooleanNumberString
undefinedfalseNaN"undefined"
nullfalse0"null"
truetrue1"true"
falsefalse0"false"
''false0''
'123'true123'123'
'1a'trueNaN'1a'
0false0"0"
1true1"1"
InfinitytrueInfinity"Infinity"
NaNfalseNaN'NaN'
{}trueNaN"[object Object]"

类型判断

  • typeof

  • instanceof

  • Object.prototype.toString

  • constructor

typeof

  1. 可以识别标准类型(null除外)

  2. 不可识别具体的对象类型(Function除外)

例:

//1. 可以识别标准类型(`null`除外)
typeof(1);//"number"
typeof("");//"string"
typeof(undefined);//"undefined"
typeof(true);//"boolean"
typeof(null);//"object"

//2. 不可识别具体的对象类型(`Function`除外)
typeof([]);//"object"
typeof({});//"object"
typeof(function(){});//"function"

instanceof

instanceof左侧为查询变量,右侧为标识对象的类

  1. 能够判别内置对象类型

  2. 不能判别原始类型

  3. 能够判别自定义类型
    例:

//1. 能够判别内置对象类型
[] instanceof Array;//true
/\d/ instanceof RegExp;//true

//2. 不能判别原始类型
1 instanceof Number;//false
"xiaohong" instanceof String;//false

//3. 能够判别自定义类型
function Point(x, y) {
    this.x = x;
    this.y = y;
}
var c = new Point(2,3);

c instanceof Point;//true

Object.prototype.toString.call()方法

  1. 可以识别标准类型,及内置对象类型

  2. 不能识别自定义类型
    例:

//1. 可以识别标准类型,及内置对象类型
Object.prototype.toString.call(21);//"[object Number]"
Object.prototype.toString.call([]);//"[object Array]"
Object.prototype.toString.call(/[A-Z]/);//"[object RegExp]"

//2. 不能识别自定义类型
function Point(x, y) {
    this.x = x;
    this.y = y;
}

var c = new Point(2,3);//c instanceof Point;//true
Object.prototype.toString.call(c);//"[object Object]"
  • 为了方便使用,使用函数封装如下:

function typeProto(obj) {
    return Object.prototype.toString.call(obj).slice(8,-1);
}

typeProto("guo");//"String"
typeProto({});//"Object"

constructor

constructor指向构造这个对象的构造函数本身..

  1. 可识别原始类型

  2. 可识别内置对象类型

  3. 可识别自定义类型
    例:

//1. 可识别原始类型
"guo".constructor === String;//true
(1).constructor === Number;//true
true.constructor === Boolean;//true
({}).constructor === Object;//true

//2. 可识别内置对象类型
new Date().constructor === Date;//true
[].constructor === Array;//true

//3. 可识别自定义类型
function People(x, y) {
    this.x = x;
    this.y = y;
}
var c = new People(2,3);
c.constructor===People;//true
  • 为了方便使用,使用函数封装如下:

function getConstructorName(obj) {
    return obj && obj.constructor && obj.constructor.toString().match(/function\s*([^(]*)/)[1];
}

getConstructorName(new Date());//"Date"
getConstructorName(null);//null
getConstructorName(12);//"Number"

类型判断对比表

  • 其中红色的单元格表示该判断方式不支持的类型。

类型判断对比表

参考:

  • 网易云课堂:面向对象软件开发实践之专业技能训练

  • 网易云课堂前端微专业笔记

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值