SoFunction
Updated on 2025-02-28

JS judges array

There is a question like this in the interview question. How to judge an array? What methods do you know

In fact, sometimes I know what methods, but I can't tell you at critical moments

typeof operator

typeof will return a string of this type

 var a = '123'
 (typeof(a)) //string
 var b = []
 (typeof(b)) //object
 var c = {}
 (typeof(c)) //object
 var d = null
 (typeof(d)) //object

The above sees that the array object is null. Use typeof to return all objects. This method cannot identify whether it is an array.

Prototype constructor chain method

Instantiation has a constructor property. This property points to the method that generates an array of objects.

 var a = []
 (a.__proto__.constructor) //ƒ Array() { [native code] }
 var b = {}
 (b.__proto__.constructor) //ƒ Object() { [native code] }

The above sees that the array is instantiated by the Array function and the object is instantiated by the Object function.

I think this method is OK, but the constructor property can be rewritten

  var a = []
  a.__proto__.constructor = Object
  (a.__proto__.constructor) //ƒ Object() { [native code] }

You can see that this is turned into an array and judged as an object, so this method is not the best

instanceof

This method is to determine whether the object pointed to by the prototype attribute of a constructor is on another prototype chain to detect the object.

  var a = []
  (a instanceof Array) //Array true can be found on the prototype chain of the a object  (a instanceof Object) //true Objects can also be found on the prototype chain

The above is not particularly good either. It cannot tell whether it is an array or an object.

General method toString

toString() method returns the string that shows this object

  var a= '123'
  (()) //123
  var b = [1,2,3]
  (()) //1,2,3
  var c = {}
  ()) //[object Object]

You can see that only objects return object type

Returns [object type] type represents the type of the object

Use the Object toString method to determine the object to use

 var a =[]
 (a) //[object Array]

This object toString method can determine whether it is an array

But here I pay attention to a situation where toString() can also be changed on the object prototype

(XX)

Personally, I still feel that using the general method toString() method is reliable

Summarize

The above is the JS judgment array introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!