Home > Article > Web Front-end > How to get the type of javascript variable
Methods to obtain JavaScript variable types: 1. Use the typeof operator, syntax "typeof variable"; 2. Use jQuery's "$.type()" method; 3. Get the type through the constructor.
The operating environment of this tutorial: windows7 system, javascript1.8.5&&jquery1.10.0 version, Dell G3 computer.
In JavaScript, how to accurately obtain the type name of a variable is a frequently asked question.
But often it is not possible to obtain the precise name of a variable, or the method in jQuery must be used. Here I The three methods of obtaining variable types through typeof, jQuery.type and constructors will be introduced in detail.
I hope it can help you.
At first glance when I saw the question, some Students may think of the typeof operator.
In the JavaScript language, it is given to use the typeof operator to obtain the basic type. The type name. (Note that it is not a basic type)
This is all the usage of typeof
01-typeof.htm
console.log('typeof of 10 ~~~~' +typeof 10); console.log('typeof of "a" ~~~~' +typeof 'a'); console.log('typeof of true ~~~~' +typeof true); console.log('typeof of {} ~~~~' +typeof {}); console.log('typeof of /123/ ~~~~' +typeof /123/); console.log('typeof of function(){} ~~~~' +typeof function(){}); console.log('typeof of undefined ~~~~' +typeof undefined); console.log('typeof of null ~~~~' +typeof null);
This is the result
According to the above printing results, summarize the following points to pay attention to
typeof (reference type) Except for functions, they are all 'object', such as typeof /123/
typeof null is 'object'
typeof undefined is 'undefined', usually, if you use two equal signs, null = = undefined is true.
Common usage of converting to numbers is "10"-0. If the conversion is not successful, NaN is returned. Due to a characteristic of NaN: NaN != NaN, so the judgment Common practices for success or failure of conversion: (This is also what I found by looking at the jQuery source code. Reading the jQuery source code 100 times is not enough) ("10x" - 0) == ("10x" - 0 ); // The result is false!
// 先申明一个对象,目的是用来做映射 var class2type = {}; // 申明一个core_toString() 的方法,得到最原始的toString() 方法,因为在很多对象中,toStrintg() 已经被重写 var core_toString() = class2type.toString;
// 这里为 toStrintg() 后的结果和类型名做一个映射,申明一个core_toString() 后的结果,而值就是类型名 jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); });Because the Object.prototype.toString() method call result is as follows
var core_toString = {}.toString; console.log( core_toString.call(1) ); console.log( core_toString.call("11") ); console.log( core_toString.call(/123/) ); console.log( core_toString.call({}) ); console.log( core_toString.call(function(){}) ); console.log( core_toString.call([]) ); console.log( core_toString.call(true) ); console.log( core_toString.call(new Date()) ); console.log( core_toString.call(new Error() )); console.log( core_toString.call(null) ); console.log( core_toString.call(undefined) ); console.log( String(null) ); console.log( String(undefined) );The above print result is the same as
class2type[ "[object " + name + "]" ] = name.toLowerCase();Coincidentally!This is the core method of jQuery.type
type: function( obj ) { if ( obj == null ) { return String( obj ); } // Support: Safari <= 5.1 (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; },
Note, why null or undefined are discussed separately, because in some versions In the browserIf it is an object type, another: Because in some lower version browsers ,typeof /123/ will return "function" instead of "object", so you need to determine whether it is a function. You must understand that
console.log(core_toString.call(null)); console.log(core_toString.call(undefined));This will report an error!
typeof obj === function is not discussed for functions, because functions The type itself can be obtained through typeof.
typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ]It will directly return the result of the key-value pair in class2type. If not, then it must be the basic type, and it can be obtained through typeof.
class2type[ core_toString.call(obj) ] || "object" : // 这是防止一些未知情况的,如果未取到,就返回objectBut
jQuery.type There is a big flaw
This is a custom typefunction Person(){ this.name = 'pawn'; } var p = Person.toString();
// Note that [object Object] will be printed here, Through the above method, the precise custom type cannot be obtainedNext, we obtain the precise type through the constructorThis is also a big flaw!
function Person(){ this.name = 'pawn'; } console.log(Person.prototype.constructor === Person);
Found that these two things are actually the same thing However, in some cases, you need to write like this
function Person(){ this.name = 'pawn'; } Person.protype = { XX: ... , xx: ... , ... }Doing so will overwrite the original prototype method, then construcor will It no longer exists. This is the object that must be explicitly declared.
Person.protype = { construction: Person, XX: ... , xx: ... , ... }In jQuery, this is how it is done.
jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem;
The method of encapsulating jQuery objects is also very worthwhile. Research
也就是,如果调用一个函数的toString() 方法.那么就会打印这个函数的函数体.
好了,经过上面两个步骤,你明白我要做什么了吗?
如何通过构造函数来获得变量的类型?
var getType = function(obj){ if(obj == null){ return String(obj); } if(typeof obj === 'object' || typeof obj === 'fucntion'){ ... }else{ // 如果不是引用类型,那么就是基本类型 return typeof obj } }
function Person(){ this.name = 'pawn'; } var p = new Person(); console.log(p.constructor);
现在要做的事 : 如何将Person 提取出来呢?
毋庸置疑,字符串切割那一套肯定可以办到,但是太 low 啦!
这里,我使用正则将Person提取出来
var regex = /function\s(.+?)\(/ function Person(){ this.name = 'pawn'; } var p = new Person(); var c = p.constructor var regex = /function\s(.+?)\(/; console.log('|' + regex.exec(c)[1] + '|');
其实,除了上面的正则,每个函数还有一个name属性,返回函数名,但是ie8 是不支持的.
因此上面的代码可以写为:
var getType = function(obj){ if(obj == null){ return String(obj); } if(typeof obj === 'object' || typeof obj === 'function'){ var constructor = obj.constructor; if(constructor && constructor.name){ return constructor.name; } var regex = /function\s(.+?)\(/; return regex.exec(c)[1]; }else{ // 如果不是引用类型,那么就是基本;类型 return typeof obj; } };
但是上面的代码太丑啦,将其简化
var getType = function(obj){ if(obj == null){ return String(obj); } if(typeof obj === 'object' || typeof obj === 'function'){ return obj.constructor && obj.constructor.name.toLowerCase() || /function\s(.+?)\(/.exec(obj.constructor)[1].toLowerCase(); }else{ // 如果不是引用类型,那么就是基本类型 return typeof obj; } };
还是比较麻烦,继续简化
var getType = function(obj){ if(obj == null){ return String(obj); } return typeof obj === 'object' || typeof obj === 'function' ? obj.constructor && obj.constructor.name && obj.constructor.name.toLowerCase() || /function\s(.+?)\(/.exec(obj.constructor)[1].toLowerCase(): typeof obj; };
好了,已经全部弄完了,写个代码测试一下:
function Person(){ this.name = 'pawn'; } var p = new Person(); console.log(getType(p)); console.log(getType(1)); console.log(getType("a")); console.log(getType(false)); console.log(getType(/123/)); console.log(getType({})); console.log(getType(function(){})); console.log(getType(new Date())); console.log(getType(new Error())); console.log(getType( null)); console.log(getType( undefined));
【推荐学习:javascript高级教程】
The above is the detailed content of How to get the type of javascript variable. For more information, please follow other related articles on the PHP Chinese website!