Js get a type judgment

For some flexible or generic function, the input parameter type according to need, to perform some logic or simple error. Therefore, to accurately determine the type of data is particularly important.

The first model, which is most likely to think of ways, typeof. It can be easily judged that the majority of data types, and null array but may be mistaken for the type of object.

The second way, instanceof, but its logic is based on the judgment instance, across instances or examples of problems will arise, and modify _proto_ will affect the result of the judgment.

The third way is the most recommended one, Object.prototype.toString.call ()

isType function (type, target) { 
   var = Object.prototype.toString.call STR (target); // [Object Xxx] 
   return str.indexOf (type) = -. 1 to true:!? to false; 
} 
// note type the first letter is capitalized 
isType ( 'the Array', []); // to true 
isType ( 'null', null); // to true

  

Guess you like

Origin www.cnblogs.com/diyichen/p/11306246.html