Determine whether a variable type is an array or an object

Because whether it is an array or an object, the return value of the typeof operation is object, so there is a need to distinguish between the array type and the object type:

Side 1: Through the length attribute: In general, the object does not have a length attribute value, its value is undefiend, and the length value of the array is of type number

  Disadvantage: Very impractical. When the property of the object has length and its value is number (such as a class array), this method is invalid, and it is not recommended to use it. Just take a look.

*Square 2: Judging and distinguishing by instanceof


var arr = [1, 2, 3];
        var obj = {
            name: 'lyl',
            age: 18,
            1: 'name'
        }
        console.log(arr instanceof Array); //true
        console.log(obj instanceof Array); //false


*Part 3: through the constructor

  

copy code
     var arr = [1, 2, 3 ];
        var obj = {
            name: 'lyl',
            age: 18,
            1: 'name'
        }
        console.log(arr.constructor === Array); //true
        console.log(obj.constructor === Array); //false
copy code

*Square 4: Through the toString() method, the toString() method defined by the array prototype and the object prototype is different

  Principle reference: http://www.cnblogs.com/ziyunfei/archive/2012/11/05/2754156.html

  

copy code
     var arr = [1, 2, 3 ];
        var obj = {
            name: 'lyl',
            age: 18,
            1: 'name'
        }
        console.log(Object.prototype.toString.call(arr) === '[object Array]'); //true
        console.log(Object.prototype.toString.call(boj) === '[object Array]'); //false
copy code

 

方五:随便找一个数组仅有的方法,来判断数组和对象谁有该方法即可(样例以sort来举例)

  

copy code
     var arr = [1, 2, 3];
        var obj = {
            name: 'lyl',
            age: 18,
            1: 'name'
        }
   console.log(arr.sort
=== Array.prototype.sort); //true console.log(obj.sort === Array.prototype.sort); //false
copy code

 

  

   总结:方法应用权重:

    优先使用方四toString,因为该方法几乎无缺陷。

    Next, you can use the second instanceof and the third constructor

    The rest of the methods can be played, not practical


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325862087&siteId=291194637