The content of this article is an introduction (code) about the method of judging JavaScript data type. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. The commonly used typeof
is not friendly to the judgment of array, object, and null. You can see the execution results in the figure below.
var obj = { number:123, string: '123', bool: true, obj: {}, arr: [], n: null, undef: undefined, fn: function () {} } for(key in obj) { console.log(key + ": " + typeof obj[key]) }
instanceof tests whether the constructor's prototype attribute appears anywhere in the object's prototype chain.
If you understand the prototype chain, you will know the complexity of the prototype chain. The value obtained by instanceof is not fixed. It will search along the prototype chain. The most obvious thing is that all basic data types inherit from Object .protype.
[任何数据类型] instanceof Object > true
As shown below:
The following is the best, most comprehensive, and most effective compatibility solution:
There are two implementation methods (prototype method and global method) below, which you can choose according to your own needs.
(function () { function isType(type,data) { // data是全局方法时使用的,原型方法可不填 return Object.prototype.toString.call(data || this) === '[object ' + type + ']' } // 全局方法支持null和undefined // window.isType = isType // 添加到数据类型的原型中,不支持null和undefined Object.defineProperty(Object.prototype,'isType',{ value:isType, writable:true, enumerable:false, configurable:true }); })()
Usage:
var str = 'abc'; // 全局方法 isType('String', str) // True // 原型方法 str.isType('String')
Test code:
var obj = { test: { number:123, string: '123', obj: {}, bool: true, arr: [], n: null, undef: undefined, fn: function () { } } } // 原型方法不支持null和undefined,请用“===” console.log(obj.test.number.isType('Number')) console.log(obj.test.number.isType('String')) console.log(obj.test.string.isType('String')) console.log(obj.test.string.isType('Number')) console.log(obj.test.obj.isType('Object')) console.log(obj.test.obj.isType('Array')) console.log(obj.test.arr.isType('Array')) console.log(obj.test.arr.isType('Object')) console.log(obj.test.fn.isType('Function')) console.log(obj.test.fn.isType('Object'))
This article is all over here, more others For exciting content, you can pay attention to the JavaScript Video Tutorial column on the PHP Chinese website! ! !
The above is the detailed content of Introduction to methods of judging data types in JavaScript (code). For more information, please follow other related articles on the PHP Chinese website!