Method of JS Judging type

Source: Internet
Author: User

In the actual project development, may often encounter data type of judgment, I also often go to degree niang, not carefully summed up, recently idle down to do a summary bar.

The basic data types of JavaScript are: Undefined, Null, Boolean, number, String. There is also a reference data type object, and on the basis of object to inherit more types, such as array,date,function, of course, including our own created constructors;

That how more rigorous to judge the type of data, in the development of the more important, the degree Niang saw a lot of methods, it boils down to three kinds:

1. Constructor (constructor)

The constructor property returns a reference to the array function that created this object, (A.constructor = = array)//A constructor for the instance is an array? True or False

Console.log ([].constructor = = Array); Console.log ({}.constructor = = Object); Console.log ("string". Constructor = = String); Console.log ((123). constructor = = number); Console.log (true.constructor = = Boolean);

2. instanceof (example)

instance, hence the name of righteousness, examples, examples, so instanceof used to judge whether a variable is an instance of an object

var a=[];console.log (a instanceof Array)//return True

3. toString

This method is more complex, do not do too much explanation, the following:

var arr = [];object.prototype.tostring.call (arr) = = ' [Object Array] ';

The method is more rigorous, and the corresponding other types of data are judged as: [Object object],[object String],[object number],[object Boolean]

Refer to the experience of other bloggers and some personal summary, if there is infringement, please contact me in time, qq:435641688, thank you

Method of JS Judging type

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.