How to determine the data type

Posted by hesketh on Mon, 06 Jul 2020 17:54:22 +0200

Use typeof to determine data type
(1) Judging basic data types

//Number type
typeof 1;//"number"
//Boolean type
typeof true;// "boolean"
//String type
typeof "zzz";// "string"
typeof  undefined;// "undefined"
function Person(name, age) { = name;
    this.age = age;
var person = new Person("Rose", 18);
typeof person;//"object"

Using typeof to determine data types in JavaScript, you can only distinguish between five basic types: number, string, undefined, boolean, and object.
Arrays, functions, and objects are intricately related, and typeof returns a uniform "object" string.

The type of value type is typeof, and the type of reference type is instanceof.

Use Object.prototype Native toString() method on to determine data type
(1) Judging basic types;//"[object Null]";//"[object Undefined]""abc");//"[object String]";//"[object Number]";//"[object Boolean]"

(2) Determining the Type of Native Reference

//Function type
Function fn(){console.log("test");};//"[object Function]"
//Date type
var date = new Date();;//"[object Date]"
//Array type
var arr = [1,2,3];;//"[object Array]"
//regular expression
var reg = /[hbc]at/gi;;//"[object Array]"
//Custom Type
function Person(name, age) { = name;
    this.age = age;
var person = new Person("Rose", 18); ); //"[object Object]"
//It is obvious that this method does not accurately determine that person is an instance of the Person class, it can only be usedinstanceof Operators to make judgments, as follows:
console.log(person instanceof Person);//Output result is true

(3) Judging native JSON objects

var isNativeJSON = window.JSON &&;
console.log(isNativeJSON);//The output is "[object JSON]" which indicates that the JSON is native, otherwise it is not;

Be careful:Object.prototype.toString() itself is allowed to be modified, and what we are discussing now isObject.prototype.toStringThe application of this method assumes that the toString() method has not been modified as a precondition.

Topics: JSON Javascript