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"
//Undefined
typeof  undefined;// "undefined"
//object
function Person(name, age) {
    this.name = 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.prototype.toString.call(null);//"[object Null]"
Object.prototype.toString.call(undefined);//"[object Undefined]"
Object.prototype.toString.call("abc");//"[object String]"
Object.prototype.toString.call(123);//"[object Number]"
Object.prototype.toString.call(true);//"[object Boolean]"

(2) Determining the Type of Native Reference

//Function type
Function fn(){console.log("test");}
Object.prototype.toString.call(fn);//"[object Function]"
//Date type
var date = new Date();
Object.prototype.toString.call(date);//"[object Date]"
//Array type
var arr = [1,2,3];
Object.prototype.toString.call(arr);//"[object Array]"
//regular expression
var reg = /[hbc]at/gi;
Object.prototype.toString.call(arr);//"[object Array]"
//Custom Type
function Person(name, age) {
    this.name = name;
    this.age = age;
}
var person = new Person("Rose", 18);
Object.prototype.toString.call(person ); //"[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 && Object.prototype.toString.call(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