How to tell if a variable is an array, function, or object type in JavaScript

Source: Internet
Author: User

Array

ECMAScript5 Array.isarray is the native method of judging arrays, IE9 and above support. For compatibility, in browsers that do not have this method, you can use Object.prototype.toString.call (obj) = = = ' [Object Array] ' instead.

var IsArray = Array.isarray | | function (obj) {return Object.prototype.toString.call (obj) = = = ' [Object Array] ';}


Function

The simplest and best-performing approach is to typeof obj = = ' function '. The most reliable way to consider the bugs of some version browsers is Object.prototype.toString.call (obj) = = = ' [Object Function] '.

var isfunction = function (obj) {return Object.prototype.toString.call (obj) = = = ' [Object function] ';} if (typeof/./! = ' function ' && typeof int8array! = ' object ') {isfunction = function (obj) {return typeo    F obj = = ' function '; }}


Object

In JavaScript, a complex type is an object, and a function is an object. For the above 2 use typeof, you can get ' object ' and ' function ' separately. Also, the case of null values is excluded, because typeof null gets the ' object ' as well.

var isobject = function (obj) {var type = typeof obj; return type = = = ' function ' | | Type = = = ' object ' &&!! obj;}


How to tell if a variable is an array, function, or object type in JavaScript

Related Article

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.