Determine whether a variable type is an object or an array

Source: Internet
Author: User

Because either an array or an object, the return value of the operation for TypeOf is object, so there is a need to differentiate between the array type and the object type:

Fang Yi: Through the Length property: In general, the object has no Length property value, its value is undefiend, and the length value of the array is number type

Cons: Very impractical, when the object's property exists length, and its value is number (such as an array of classes), then the method is invalid, not recommended, look at it.

* Square Two: Judge the distinction by instanceof

  

        var arr = [1, 2, 3];        var obj = {            name: ' lyl ',            age:18, 1: ' Name '/    ///False 

* Party three: through constructor

  

var arr = [1, 2, 3];        var obj = {            name: ' lyl ',            age:18, 1: ' Name '/     ///False 

* Square Four: The ToString () method is different for array prototypes and object prototypes defined by the ToString () method

Principle Reference: Http://www.cnblogs.com/ziyunfei/archive/2012/11/05/2754156.html

  

var arr = [1, 2, 3];        var obj = {            name: ' lyl ',            age:18, 1: ' Name '/     ///False 

Square Five: Find an array of the only methods to determine the array and the object who has the method (example with sort)

  

var arr = [1, 2, 3];        var obj = {            name: ' lyl ',            age:18, 1: ' Name ' }
//false

  

Summary: Methods apply weights:

Priority is to use four ToString, because the method is almost free of defects.

The second can be used side two instanceof and square three constructor

The rest of the way to play, not practical

Determine whether a variable type is an object or an array

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.