当前位置:网站首页>JS five methods to judge the most complete data types
JS five methods to judge the most complete data types
2022-04-22 06:42:00 【Bring in the red moon】
One 、js data type
number // Numbers Types include integers and floating point numbers
string // character string String has length attribute
boolean // Boolean value There are only two values for this type ,true and false
function // function Usually defined using function declaration syntax
object // object A collection of properties and methods
null // This type is seen as shorting the object pointer , Is also an empty object reference
undefined // There is only one value, i.e undefined value , Use var Variable declared but not initialized
Two 、 Judge data type
1. The most common way to judge :typeof
typeof 1;//'number'
typeof true;//'boolean'
typeof '';//'string'
typeof undefined;//'undefined'
typeof function (){};'function'
//typeof The types returned are all in string form , Attention should be paid to , for example :
typeof '' == "string" //true
typeof '' == String //false
//typeof Can be judged function The type of ; In judgment Division Object Type of object is more convenient .
// stay JS in , It works typeof Data types that can be detected , Best use typeof To detect
//typeof It is a sharp tool for basic data type detection ( But not including null); You can also detect whether it is a function , But when detecting objects ,
// It is not clear which class each object belongs to , Because the return values are object.
2. A method of judging a known object type : instanceof
//instanceof Is an operator , The return value is a Boolean value
//instanceof Is the test reference data type , The basic data type cannot be detected
var arr = [];
var fn = function(){};
arr instanceof Array;//true
// But as long as there is a constructor on the prototype chain, it will return true, So this test result is not very accurate
arr instanceof Object;//true
//instanceof The following must be the object type , And the case cannot be wrong , Suitable for some conditional selection or branch .
fn instanceof Function // true
fn instanceof function // false
3. Based on the constructor Judge : constructor
//constructor This property exists on the prototype of the constructor , Pointing constructor
// Objects can pass through __proto__ Find this property on the prototype of its class
var arr = [];
arr.constructor === Array;//true
arr.constructor === Object;//false
//arr Found through prototype chain search constructor Yes Array, therefore Object The judgment is wrong
constructor It is more accurate to judge the type of the object , But there will be errors in class inheritance
function Fn() {}
Fn.prototype = new Array();
var fn = new Fn();
fn.constructor === Array; //true
//fn It's an object , But its constructor points to Array yes true
function A(){};
function B(){};
A.prototype = new B(); //A Inherited from B
var aObj = new A();
aobj.constructor === B //true;
aobj.constructor === A // false;
Both direct and indirect inheritance of objects will be reported true
aobj instanceof B //true;
aobj instanceof B //true;
solve construtor The problem is usually to make the object constructor Manually point to yourself :
aobj.constructor = A; // Assign your own class to the... Of the object constructor attribute
aobj.constructor === A //true;
aobj.constructor === B //false; // The base class will not report true 了 ;
4. Cumbersome method : prototype
// stay Object The basic class defines this toString() Method , Is used to detect data types ;
// Follow string 、 Numbers 、 Defined on Boolean prototypes toString() The basic usage of the method is to convert strings
console.log(Object.prototype.toString.call(1));//[object Number]
console.log(Object.prototype.toString.call(''));//[object String]
console.log(Object.prototype.toString.call(true));//[object Boolean]
console.log(Object.prototype.toString.call(null));// [object Null]
console.log(Object.prototype.toString.call(undefined));//[object Undefined]
console.log(Object.prototype.toString.call([]));// [object Array]
console.log(Object.prototype.toString.call({}));// [object Object]
console.log(Object.prototype.toString.call(/^$/));//[object RegExp]
console.log(Object.prototype.toString.call((function () {})));//[object Function]
// Case cannot be misspelled , More trouble , Data detection should be the most accurate .
5.jquery Of $.type()
//$.type() The function is used to determine JavaScript Types of built-in objects , And returns the type name in lowercase .
// If the object is undefined or null, Then return the corresponding "undefined" or "null"
$.type( undefined ) === "undefined"
$.type() === "undefined"
$.type( window.notDefined ) === "undefined"
$.type( null ) === "null"
// If the object has an internal property [[Class]] And a browser built-in object [[Class]] identical
// Then return the corresponding [[Class]] name .
$.type( true ) === "boolean"
$.type( 3 ) === "number"
$.type( "test" ) === "string"
$.type( function(){} ) === "function"
$.type( [] ) === "array"
$.type( new Date() ) === "date"
$.type( new Error() ) === "error" // jQuery 1.9 New support
$.type( /test/ ) === "regexp"
// Everything else will return its type “object”.
// This is a very powerful method But you need to introduce jquery
// Or try to parse it yourself jquery Of $.type() Source code Encapsulate a similar method by yourself
// Like this :
var class2type={},
toString =object.prototype.toString();
function testType(obj){
return obj ==null ? String(obj) :class2type[toString.call(obj)] || "object";
}
// I haven't tested this yet I don't know if it's feasible If you can't, you can tell me I'll test again
In general, use typeof Just judge , Encounter prediction Object Type can be used instanceof or constructor Method , If it doesn't work in the front, just use $.type() Method .
版权声明
本文为[Bring in the red moon]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220556231200.html
边栏推荐
猜你喜欢

TCP和UDP区别详解

redis存入数据显示乱码问题

webService接口编写并发布与webService接口的调用(一)

Shumei technology and surging news jointly released the "network information content security insight report"

uglifyjs压缩JS

从零开始学安卓(kotlin)五——UI

小程序自定义原生底部导航

The installation of redis is started and used by rookies (Windows)

MYSQL事务之事务隔离级别

Mvcc transaction isolation in PostgreSQL
随机推荐
Sort sort
创新实训(十)
Spent four days painstakingly writing all the notes of MySQL, which is very suitable for beginners.
Shumei technology was honored as the "top 100 scientific and technological innovation of private enterprises in Beijing"
MYSQL 查看优化器后执行得SQL语句详情
TiDB分表唯一主键ID——sequence 与gorm无法获取主键的解决
pixel手机救砖教程
js判断PC端或移动端
Join hands to strengthen the ability of "content audit" and achieve strategic cooperation between rongyun and digital beauty technology!
Mapping of oid and relfilenode in PostgreSQL
滚动条的多种样式
一套sql语句同时支持Oracle跟Mysql?
点击触发其他dom元素:< $refs,$el >
在微信小程序中打开的页面不能超过10个,达到10个页面后,就不能再打开新的页面
js对url进行编码和解码(三种方式区别)
毕业设计碎碎念
创新实训(七)FBV视图&CBV视图
MySQL——索引
js,jq单行文字上下滚动
ArcGIS 基于TIN地表面数据和建筑数据进行视域分析