JS Check variable type code () _javascript Tips

Source: Internet
Author: User
JavaScript examines the type of a variable and determines whether it is an integer or a string or other type, and so on.
<ptml> <pead> <title> Check variable type </title> </pead> <body> <script language= "Javascr IPT "> <!--name =" Liu Honghui "; age = 22; The type of the document.write (' name variable is: ', typeof (name), '); The type of document.write (' Age variable is: ', typeof (age), '); document.write (' Document of type is: ', typeof (document)); --> </script> </body> </ptml>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]

2, toString is used to do string conversion, but now popular to do variable type of check. Shun also wrote a function to check the type of variable, which can be used instead of typeof
Copy Code code as follows:

function GetType (o) {
var _t; Return ((_t = typeof (o)) = = "Object"? O==null && "Null" | | Object.prototype.toString.call (o). Slice (8,-1): _t). toLowerCase ();
}


Execution results:

GetType ("abc"); String
GetType (TRUE); Boolean
GetType (123); Number
GetType ([]); Array
GetType ({}); Object
GetType (function () {}); function
GetType (new Date); Date
GetType (new REGEXP); Regexp
GetType (Math); Math
GetType (NULL); Null

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.