4 Methods for JS validation data type

Source: Internet
Author: User

1.typeof can verify basic data types but reference data types (complex data types) are useless;

Summary: typeof does not recognize reference data types including bull;

2.instanceof is a two-dollar operator, the left operand is an object, and the right operand is a constructor. The expression returns true if the left-hand object is an instance object of the right-hand constructor; otherwise false

If the left operand is not an object, returns false and throws a type error exception if the right operand is not a function typeerror

Console.log (True instanceof Boolean)//Boolean
Console.log ("string" instanceof String)//String
Console.log (123 instanceof Number)//number
Console.log (undefined instanceof)//Syntax error
Console.log (function () {} instanceof Function)//function
Console.log (null instanceof NULL)//Syntax error
Console.log ([instanceof] Array)//objet
Console.log ({"Name": "Liming"} instanceof Object)//Object

Summary: null and undefined no constructors using this method will report an error!!! The base data type cannot be identified and the reference data type is all Object!!!

3.constructor

The constructor property of the instance object points to its constructor. If the object type, then output function 数据类型(){} ; NULL Undefiend error

4.object.prototype.tostring () method

The class property of an object is a string that represents the type information of the object. JavaScript does not provide a way to set this property, but there is an indirect way to query it

The Object.prototype.toString () method returns a string in the following format: [Object data Type]

Console.log (Object.prototype.toString.call ("string"));//[object string]
Console.log (Object.prototype.toString.call (1));//[object number]
Console.log (Object.prototype.toString.call (true));//[object Boolean]
Console.log (Object.prototype.toString.call (undefined));//[object undefined]
Console.log (Object.prototype.toString.call (null));//[object NULL]

4 Methods for JS validation data 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.