Three ways to distinguish between arrays and objects

Three ways to distinguish between arrays and objects


Because the type of judgment object and array are both ,typeof
Object

So sometimes it is impossible to tell if the type of a value is an object or an array.

<script type="text/javascript">

var obj = [];

//现在判断 obj 是属于社么类型的值

</script>

1.constructor

The constructor of the array isfunction Array(){...}

The constructor of the object isfunction Object() { ...}

QQ browser screenshot_20180312092307_14A73E450D3E45acAD65D25A079B29BA.jpg

2.instanceof

QQ browser screenshot_20180312093419_7B9B4D6B085A424e9E65EAC7054EB465.jpg

Check if there is an Array constructor in the prototype chain of obj,

If it returns true, that is, obj is of Array array type.

3.toString

QQ browser screenshot_20180312095422_C0A78CD309004a2aA6F9B6776EC10D23.jpg

Change the point of this and let the array call Object's to.String method.

Guess you like

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