Javascript type check implementation code _ javascript skills

Source: Internet
Author: User
One way to check the object type is to refer to a common property called constructor of all JavaScript objects. This attribute is a reference to a function originally used to construct this object. The Code is as follows:


// Check whether our number is actually a string
If (num. constructor = String)
// If yes, parse it into numbers
Num = parseInt (num );
// Check whether our string is actually an array
If (str. constructor = Array)
// If yes, use a comma to connect to the array to obtain a string
Str = str. join (',');


Table 1 shows the results of performing type checks on different types of objects using the two methods described above. The first column of the table shows the objects we are trying to find. Run typeof Variable (Variable is the value shown in the first column ). All results in this column are strings. Finally, the third column shows the result of running Variable. constructor on the objects contained in the first column. All the results in these columns are objects.

Table 1. Variable type check

-------------------------------
Variable typeof Variable. constructor
-------------------------------
{An: "object"} object Object
["An", "array"] object Array
Function () {} function Function
"A string" string String
55 number
True boolean Boolean
New User () object User
----------------------------------

Using a variable's constructor as an object type reference may be the simplest type check method. When you want to determine the exact number of parameters to be passed into your function, strict type checks may be helpful.

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.