SoFunction
Updated on 2025-03-03

Summary of JS method to detect array type

Applicable when there is only one global execution environment. If multiple frameworks are included, there are more than two different versions of Array constructors. If an array is passed from one framework to another, the passed array has different constructors from the array created natively in the second framework, that is, different types

if (value instanceof Array) {
  //Perform some operation on the array}

2. () Method

Because it is newly added to ES5, it only supports IE9+, Firefox 4+, Safari 5+, Opera 10.5+ and Chrome

if ((value)) {
  //Perform some operations on the array}

()method

It is suitable for all environments and only supports native objects. The toString() method of Object cannot detect constructor names of non-native constructors. Any constructor customized by the developer will return [object Object]

Principle: Calling the native toString() method of Object directly on any value will return a string in the format of [object NativeConstrctorName]. Each class has a class attribute inside, which specifies the constructor name in the above string.

var value = []
((value))//"[Object Array]"

Since the constructor name of the native array is independent of the scope, using the toString() method can ensure that the same value is output.

Why not use the object's own toString() method?

var value = []
(())//" "
value = ['pp','oo']
(())//"pp,oo"
value = ['pp',"oo"]
((value))//[object Array]

Array's tostring() method has been rewritten (this is true for many native objects), so it will call the toString() method on its constructor to return other strings.

You can also use this method to determine whether it is a native function or a regular expression

function isFunction(value){
    return (value) === “[object Function]”
}//Not applicable to any function implemented in IE using COM objectsfunction isRegExp(value){
    return (value) === “[object RegExp]”
}

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