Summary of JS Methods for Detecting Array Types

  • 2021-08-05 07:57:13
  • OfStack

1.instanceof

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


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

2. Array. isArray () method

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


if (Array.isArray(value)) {
  // Perform some operations on arrays  
}

3. Object. prototype. toString. call () method

Applicable to all environments, only native objects are supported, and the toString () method of Object cannot detect the constructor name of a non-native constructor. Any constructor customized by the developer will return [object Object]

How it works: Calling the native toString () method of Object directly on any value returns a string in the format [object NativeConstrctorName]. Each class has an class attribute inside, and this attribute specifies the constructor name in the above string.


var value = []
console.log(Object.prototype.toString.call(value))//"[Object Array]"

Because the constructor name of the native array is scope-independent, the toString () method guarantees a value of 1.  

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


var value = []
console.log(value.toString())//" "
value = ['pp','oo']
console.log(value.toString())//"pp,oo"
value = ['pp',"oo"]
console.log(Object.prototype.toString.call(value))//[object Array]

The tostring () method of Array is overridden (as many native objects do), so it calls the toString () method on its own constructor and returns another string

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


function isFunction(value){
    return Object.prototype.toString.call(value) ===  " [object Function] " 
}// Not applicable to IE China and Israel COM Any function implemented by the object 
function isRegExp(value){
    return Object.prototype.toString.call(value) ===  " [object RegExp] " 
}

Related articles: