Type of JS Detection object

Source: Internet
Author: User
Tags object object

In JavaScript, the most reliable way to determine what kind of built-in type an object's value belongs to is through the Object.prototype.toString method.

Example:

var array=[1,2,3];object.prototype.tostring.call (array); // "[Object Array]" var obj={name: ' Tom '};object.prototype.tostring.call (obj); // "[Object Object]" var string= ' Hi '; Object.prototype.toString.call (string); // "[Object String]" var num=1; Object.prototype.toString.call (num); // "[Object number]"

There are other ways, of course, but it's a bit troublesome.

such as TypeOf, but the typeof is not measured whether the object being detected is an object or an array, because object contains an array, such as:

var array=[1,2,3]; var obj={name: ' Tom '}; typeof Array; // "Object" typeof obj; // "Object"

You can see that the return is "object".

With instanceof, you can accurately detect JS types like Object.prototype.toString. such as:

var o=[];   instanceof Array); // true   instanceof Object); // true   var f=function() {}  instanceof function); // true   instanceof Object); //

Summary: Simple to use simple and straightforward, so with Object.prototype.toString.call (obj) this way is good.

Type of JS Detection object

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.