Home > Web Front-end > JS Tutorial > body text

4 methods for js data type detection

巴扎黑
Release: 2016-11-25 10:52:37
Original
1493 people have browsed it

1.typeof

Disadvantages: It is not very convenient to detect types such as null and Array

Js code

typeof null; //"object"

typeof []; //"object"

2.instanceof

Disadvantages: 1. Only applicable to object types

2. As long as the current class is on the prototype chain of the instance, the detected results are true

Js code

123 instanceof Number; //false

null instanceof null; //TypeError

null instanceof Object; //false

function A(){}

function B(){}

A.prototype=new B();

var aObj=new A() ;

aObj instanceof B;//true

aObj instanceof A;//true

3.constructor

Note: An error will occur during class inheritance

Js code

function A(){};

function B(){};

A.prototype = new B();

var aObj = new A();

aObj.constructor === B; //true;

aObj.constructor === A; //false;

4. Custom method implementation (more general)

Js code

function getType(o){

return Object.prototype.toString.call(o).slice(8,-1 ;

getType({}); //"Object"

getType(()=>{}); //"Function"

getType(document.createElement('div')); //"HTMLDivElement"

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template