Difference between array and object in javascript? or Array Vs Object

前端 未结 4 1639
梦毁少年i
梦毁少年i 2021-02-07 15:08

How to recognize array & object in js where typeof doesn’t come in handy?

 var arr = [], ob = {};

As everything in js are objects,

4条回答
  •  执笔经年
    2021-02-07 15:30

    var arr = [], ob = {};
    

    As everything in js are objects, even **Array is an Object but an instance of class Array

    if(typeof arr == typeof ob)  => returns true as Both are **Objects
    

    So, how will you to identify objects.

    This is where instanceof operator comes in handy, to identify whether its an array you can put a additional check cde:

    if(arr instanceof Object && arr instanceof Array) => returns true 
    if(ob instanceof Object && ob instanceof Array) => returns false 
    

提交回复
热议问题