javascript中对变量类型的推断

简介:

本文正式地址:http://www.xiabingbao.com/javascript/2015/07/04/javascript-type

在JavaScript中,有5种基本数据类型和1种复杂数据类型,基本数据类型有:UndefinedNullBooleanNumberString。复杂数据类型是ObjectObject中还细分了非常多详细的类型,比方:ArrayFunctionDate等等。今天我们就来探讨一下,使用什么方法推断一个出一个变量的类型。

在解说各种方法之前。我们首先定义出几个測试变量,看看后面的方法到底能把变量的类型解析成什么样子,以下几个变量差点儿相同包括了我们在实际编码中经常使用的类型。

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;
var date = new Date();
var reg  = /^[a-zA-Z]{5,20}$/;
var error= new Error();

1. 使用typeof检測

我们平时用的最多的就是用typeof检測变量类型了。

这次,我们也使用typeof检測变量的类型:

console.log(
    typeof num, 
    typeof str, 
    typeof bool, 
    typeof arr, 
    typeof json, 
    typeof func, 
    typeof und, 
    typeof nul, 
    typeof date, 
    typeof reg, 
    typeof error
);
// number string boolean object object function undefined object object object object

从输出的结果来看,arr, json, nul, date, reg, error 全部被检測为object类型。其它的变量能够被正确检測出来。当须要变量是否是numberstringbooleanfunctionundefined, json类型时。能够使用typeof进行推断。其它变量是推断不出类型的,包括null。

还有。typeof是区分不出arrayjson类型的。由于使用typeof这个变量时,array和json类型输出的都是object

2. 使用instance检測

在 JavaScript 中,推断一个变量的类型尝尝会用 typeof 运算符。在使用 typeof 运算符时採用引用类型存储值会出现一个问题,不管引用的是什么类型的对象,它都返回 “object”。ECMAScript 引入了还有一个 Java 运算符 instanceof 来解决问题。instanceof 运算符与 typeof 运算符相似,用于识别正在处理的对象的类型。

与 typeof 方法不同的是,instanceof 方法要求开发人员明白地确认对象为某特定类型。

比如:

function Person(){

}
var Tom = new Person();
console.log(Tom instanceof Person); // true

我们再看看以下的样例:

function Person(){

}
function Student(){

}
Student.prototype = new Person();
var John = new Student();
console.log(John instanceof Student); // true
console.log(John instancdof Person);  // true

instanceof还能检測出多层继承的关系。

好了。我们来使用instanceof检測上面的那些变量:

console.log(
    num instanceof Number,
    str instanceof String,
    bool instanceof Boolean,
    arr instanceof Array,
    json instanceof Object,
    func instanceof Function,
    und instanceof Object,
    nul instanceof Object,
    date instanceof Date,
    reg instanceof RegExp,
    error instanceof Error
)
// num : false 
// str : false 
// bool : false 
// arr : true 
// json : true 
// func : true 
// und : false 
// nul : false 
// date : true 
// reg : true 
// error : true

从上面的执行结果我们能够看到,num, str和bool没有检測出他的类型,可是我们使用以下的方式创建num,是能够检測出类型的:

var num = new Number(123);
var str = new String('abcdef');
var boolean = new Boolean(true);

同一时候,我们也要看到,und和nul是检測的Object类型,才输出的true,由于js中没有UndefinedNull的这样的全局类型,他们und和nul都属于Object类型,因此输出了true。

3. 使用constructor检測

在使用instanceof检測变量类型时。我们是检測不到number, ‘string’, bool的类型的。

因此,我们须要换一种方式来解决问题。

constructor本来是原型对象上的属性,指向构造函数。可是根据实例对象寻找属性的顺序,若实例对象上没有实例属性或方法时,就去原型链上寻找,因此,实例对象也是能使用constructor属性的。

我们先来输出一下num.constructor的内容,即数字类型的变量的构造函数是什么样子的:

function Number() { [native code] }

我们能够看到它指向了Number的构造函数。因此,我们能够使用num.constructor==Number来推断num是不是Number类型的。其它的变量也相似:

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,
    json.constructor==Object,
    func.constructor==Function,
    date.constructor==Date,
    reg.constructor==RegExp,
    error.constructor==Error
);
// 全部结果均为true

从输出的结果我们能够看出,除了undefined和null。其它类型的变量均能使用constructor推断出类型。

不过使用constructor也不是保险的,由于constructor属性是能够被改动的,会导致检測出的结果不对,比如:

function Person(){

}
function Student(){

}
Student.prototype = new Person();
var John = new Student();
console.log(John.constructor==Student); // false
console.log(John.constructor==Person);  // true

在上面的样例中,Student原型中的constructor被改动为指向到Person,导致检測不出实例对象John真实的构造函数。

同一时候,使用instaceof和construcor,被推断的array必须是在当前页面声明的!比方。一个页面(父页面)有一个框架,框架中引用了一个页面(子页面),在子页面中声明了一个array,并将其赋值给父页面的一个变量。这时推断该变量。Array == object.constructor;会返回false; 
原因: 
1、array属于引用型数据。在传递过程中。不过引用地址的传递。 
2、每一个页面的Array原生对象所引用的地址是不一样的,在子页面声明的array,所相应的构造函数。是子页面的Array对象。父页面来进行推断,使用的Array并不等于子页面的Array。切记。不然非常难跟踪问题!

4. 使用Object.prototype.toString.call

我们先不管这个是什么,先来看看他是怎么检測变量类型的:

console.log(
    Object.prototype.toString.call(num),
    Object.prototype.toString.call(str),
    Object.prototype.toString.call(bool),
    Object.prototype.toString.call(arr),
    Object.prototype.toString.call(json),
    Object.prototype.toString.call(func),
    Object.prototype.toString.call(und),
    Object.prototype.toString.call(nul),
    Object.prototype.toString.call(date),
    Object.prototype.toString.call(reg),
    Object.prototype.toString.call(error)
);
// '[object Number]' '[object String]' '[object Boolean]' '[object Array]' '[object Object]'
// '[object Function]' '[object Undefined]' '[object Null]' '[object Date]' '[object RegExp]' '[object Error]'

从输出的结果来看,Object.prototype.toString.call(变量)输出的是一个字符串,字符串里有一个数组,第一个參数是Object,第二个參数就是这个变量的类型,并且,全部变量的类型都检測出来了,我们只须要取出第二个參数就可以。

或者能够使用Object.prototype.toString.call(arr)=="object Array"来检測变量arr是不是数组。

我们如今再来看看ECMA里是是怎么定义Object.prototype.toString.call的:

Object.prototype.toString( ) When the toString method is called, the following steps are taken: 
1. Get the [[Class]] property of this object. 
2. Compute a string value by concatenating the three strings “[object “, Result (1), and “]”. 
3. Return Result (2)

上面的规范定义了Object.prototype.toString的行为:首先,取得对象的一个内部属性[[Class]],然后根据这个属性,返回一个相似于”[object Array]”的字符串作为结果(看过ECMA标准的应该都知道,[[]]用来表示语言内部用到的、外部不可直接訪问的属性。称为“内部属性”)。利用这种方法,再配合call,我们能够取得不论什么对象的内部属性[[Class]]。然后把类型检測转化为字符串比較,以达到我们的目的。

5. jquery中$.type的实现

在jquery中提供了一个$.type的接口,来让我们检測变量的类型:

console.log(
    $.type(num),
    $.type(str),
    $.type(bool),
    $.type(arr),
    $.type(json),
    $.type(func),
    $.type(und),
    $.type(nul),
    $.type(date),
    $.type(reg),
    $.type(error)
);
// number string boolean array object function undefined null date regexp error

看到输出结果,有没有一种熟悉的感觉?对,他就是上面使用Object.prototype.toString.call(变量)输出的结果的第二个參数呀。

我们这里先来对照一下上面全部方法检測出的结果,横排是使用的检測方法, 竖排是各个变量:

类型推断 typeof instanceof constructor toString.call $.type
num number false true [object Number] number
str string false true [object String] string
bool boolean false true [object Boolean] boolean
arr object true true [object Array] array
json object true true [object Object] object
func function true true [object Function] function
und undefined false - [object Undefined] undefined
nul object false - [object Null] null
date object true true [object Date] date
reg object true true [object RegExp] regexp
error object true true [object Error] error
长处 使用简单,能直接输出结果 能检測出复杂的类型 基本能检測出全部的类型 检測出全部的类型 -
缺点 检測出的类型太少 基本类型检測不出,且不能跨iframe 不能跨iframe,且constructor易被改动 IE6下undefined,null均为Object -

这样对照一下,就更能看到各个方法之间的差别了,并且Object.prototype.toString.call$type输出的结果真的非常像。我们来看看jquery(2.1.2版本号)内部是怎么实现$.type方法的:

// 实例对象是能直接使用原型链上的方法的
var class2type = {};
var toString = class2type.toString;

// 省略部分代码...

type: function( obj ) {
    if ( obj == null ) {
        return obj + "";
    }
    // Support: Android<4.0, iOS<6 (functionish RegExp)
    return (typeof obj === "object" || typeof obj === "function") ?
        (class2type[ toString.call(obj) ] || "object") :
        typeof obj;
},

// 省略部分代码... 

// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
    class2type[ "[object " + name + "]" ] = name.toLowerCase();
});

我们先来看看jQuery.each的这部分:

// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
    class2type[ "[object " + name + "]" ] = name.toLowerCase();
});

//循环之后,`class2type`的值是: 
class2type = {
    '[object Boolean]' : 'boolean', 
    '[object Number]'  : 'number',
    '[object String]'  : 'string',
    '[object Function]': 'function',
    '[object Array]'   : 'array',
    '[object Date]'    : 'date',
    '[object RegExp]'  : 'regExp',
    '[object Object]'  : 'object',
    '[object Error]'   : 'error'
}

再来看看type方法:

// type的实现
type: function( obj ) {
    // 若传入的是null或undefined。则直接返回这个对象的字符串
    // 即若传入的对象obj是undefined。则返回"undefined"
    if ( obj == null ) {
        return obj + "";
    }
    // Support: Android<4.0, iOS<6 (functionish RegExp)
    // 低版本号regExp返回function类型;高版本号已修正,返回object类型
    // 若使用typeof检測出的obj类型是object或function。则返回class2type的值,否则返回typeof检測的类型
    return (typeof obj === "object" || typeof obj === "function") ?
        (class2type[ toString.call(obj) ] || "object") :
        typeof obj;
}

typeof obj === "object" || typeof obj === "function"时,就返回class2type[ toString.call(obj)

到这儿,我们就应该明白为什么Object.prototype.toString.call和$.type那么像了吧,事实上jquery中就是用Object.prototype.toString.call实现的。把’[object Boolean]’类型转成’boolean’类型并返回。若class2type存储的没有这个变量的类型,那就返回”object”。 
除了”object”和”function”类型。其它的类型则使用typeof进行检測。即numberstringboolean类型的变量,使用typeof就可以。

本文正式地址:http://www.xiabingbao.com/javascript/2015/07/04/javascript-type








本文转自mfrbuaa博客园博客,原文链接:http://www.cnblogs.com/mfrbuaa/p/5202979.html,如需转载请自行联系原作者

相关文章
|
23天前
|
JavaScript
变量和函数提升(js的问题)
变量和函数提升(js的问题)
|
23天前
|
JavaScript
常见函数的4种类型(js的问题)
常见函数的4种类型(js的问题)
11 0
|
1月前
|
JSON JavaScript 前端开发
解决js中Long类型数据在请求与响应过程精度丢失问题(springboot项目中)
解决js中Long类型数据在请求与响应过程精度丢失问题(springboot项目中)
42 0
|
25天前
|
JavaScript 前端开发
JavaScript 中如何检测一个变量是一个 String 类型?
JavaScript 中如何检测一个变量是一个 String 类型?
21 2
|
22天前
|
JavaScript 前端开发
JavaScript数组的功能内置类型
数组是JavaScript的内置类型,JavaScript数组的功能特别强大。下面简单介绍一下JavaScript数组。
|
25天前
|
存储 JavaScript 前端开发
JavaScript 中松散类型的理解
JavaScript 中松散类型的理解
26 3
|
1月前
|
JavaScript 前端开发 容器
javascript中的变量定义
javascript中的变量定义
|
1月前
|
存储 JavaScript 前端开发
编程笔记 html5&css&js 075 Javascript 常量和变量
编程笔记 html5&css&js 075 Javascript 常量和变量
|
1月前
|
Web App开发 iOS开发
编程笔记 html5&css&js 026 HTML输入类型(2/2)
编程笔记 html5&css&js 026 HTML输入类型(2/2)
|
1月前
|
移动开发 数据安全/隐私保护 HTML5
编程笔记 html5&css&js 025 HTML输入类型(1/2)
编程笔记 html5&css&js 025 HTML输入类型(1/2)