Data types include basic data type and reference data type.
Basic data types: Null, undefined, String, Number, Boolean, Symbol
Reference data types: Object, Array, Date, Function, Error, RegExp, Math, Number, String, Boolean, Globle
Judgment method of data types mainly include: typeof, intanceof, construtor, Object. The prototype. The call (), toString. IsArray (whether can only judge array)
It is recommended to use the Object. The prototype. ToString. Call ()
Typeof (commonly used)
The return is a String, often used to determine basic data types: String, Number, Undefined, Boolean, Function, but objects and Null and arrays return Object.
console.log(typeof ' ');//string
console.log(typeof 1);//number
console.log(typeof true);//boolean
console.log(typeof undefined);//undefined
console.log(typeof function () {});//function
console.log(typeof {});//object
console.log(typeof null);//object
console.log(typeof [1.2.3]);//object
Copy the code
To determine whether a variable exists, use typeof:
If (a) is not specified, an error is reported: a is not defined.
if (typeofa ! ='undefined') {
console.log("A variable exists.");
} else {
console.log("The A variable does not exist.");
}
If (a) is not defined, an error is reported if a is not defined
if (a) {
console.log("1111");
} else {
console.log("222");
}
Copy the code
Second, the instanceof
Only suitable for detecting reference types, not primitive data types, and returns a Boolean value.
Any constructor on the prototype chain will return true. Instanceof is not very accurate.
How instanceof works:
Checks whether the constructor’s prototype property appears on an instance’s object prototype chain.
For example: A instanceof B refers to whether B’s prototype appears on A’s prototype chain. (A is the instance object, B is the constructor);
var arr = [];
console.log(arr);
console.log(arr instanceof Array);//true
console.log(arr instanceof Object);//true
let Person = function(){};
let p1 = new Person();
console.log(p1 instanceof Person);//true
let s1 = new String('leaf');
console.log(s1 instanceof String);//true
let str = "ice";
console.log(str instanceof String);//false
Copy the code
The implementation principle of Instanceof can be referred to:
Return true until the same prototype object is found, false otherwise
function myInstanceof(left, right) {
// Use typeof to determine the underlying data type
if (typeofleft ! = ='object' || left === null) {
return false;
}
// getPrototypeOf is the API of the Object Object
let proto = Object.getPrototypeOf(left);
while (true) {
if (proto === null) {
return false;
}
// Find the same prototype object, return true
if (proto === right.prototype) {
return true
}
proto = Object.getPrototypeOf(proto); }}Copy the code
(4). (4).
The constructor property holds an attribute on the constructor’s prototype chain that points to the constructor, which can be viewed directly by accessing __proto__ on the constructor.
var arr = [];
console.log(arr);
console.log(arr.constructor === Array);
Copy the code
Since the attributes of the prototype chain can be modified and constructor may be modified, this method is not recommended:
function Person(){
}
Person.prototype = new Array(a);// Modify the prototype chain on the Person constructor
var myFather = new Person();
console.log(Person.constructor === Array);//false
Copy the code
Four, the Object. The prototype. ToString. Call () (recommended!!!)
Return a string in the format of “[object XXX]”, XXX being the specific data type, including: String, Number, Boolean, Undefined, Null, the Function, the Date, the Array, the RegExp, Error, HTMLDocument, etc.
ToString is a method on the Object prototype that returns the specific type of its caller by default, strictly speaking, the type of the Object to which the toString runtime this refers.
let myNull = null;
console.log(Object.prototype.toString.call(myNull));//[object Null]
let myUndefined = undefined;
console.log(Object.prototype.toString.call(myUndefined));//[object Undefined]
let str = 'leaf';
console.log(Object.prototype.toString.call(str));//[object String]
let arr = [];
console.log(Object.prototype.toString.call(arr));//[object Array]
let boolean = true;
console.log(Object.prototype.toString.call(boolean));//[object Boolean]
let myDate = new Date(a);console.log(Object.prototype.toString.call(myDate));//[object Date]
let myFun = function (){};
console.log(Object.prototype.toString.call(myFun));//[object Function]
let myError = new Error(a);console.log(Object.prototype.toString.call(myError));//[object Error]
let myReg = /leaf/;
console.log(Object.prototype.toString.call(myReg));//[object RegExp]
Copy the code
The simplest method of judgment is an array, remember is object. The prototype. ToString. Call ()
IsArray ();
The isArray() method is used to determine whether an object is an array. Return true if the object is an array, false otherwise.
const a = []; const b = {}; Array.isArray(a); //true Array.isArray(b); //falseCopy the code
6. Relevant interview questions
To achieve a global general data type judgment method
function getType(obj) {
if (typeofobj ! = ='object') {
return (typeof obj)
}
return Object.prototype.toString.call(obj).replace(/^\[object (\S+)\]$/.'$1');
}
console.log(getType([]));//Array
console.log(getType(null));//Null
console.log(getType('123'));//stringRegular review:// ^ The start of the match
// $matches the end of the input
// * Matches the previous expression 0 or more times
// \s matches a whitespace character, including a space, TAB, page feed, line feed, etc
// The "g" after the regular expression is a representation of a global search option or flag that looks for and returns all matches across the string
Copy the code
How to determine an array?
There are several ways to determine arrays:
- instanceof
- Use the isArray method of the Array object
- Object.prototype.toString.call( )
1, instanceof
if (arr instanceof Array= = =false) {
console.log("Non-array");
return false
}
return true
Copy the code
2. Use the isArray method of the Array object
The isArray() method is used to determine whether an object is an array.
Return true if the object is an array, false otherwise.
const a = [];
const b = {};
Array.isArray(a);//true
Array.isArray(b);//false
Copy the code
3, the Object. The prototype. ToString. Call ()
let arr = [];
if(Object.prototype.toString.call(arr) === "[object Array]") {console.log("I'm an array");
return true
}
console.log("I'm not an array");
return false
Copy the code
How to determine an empty object?
There are several ways to determine an empty object:
-
for… In traverses object properties
-
Using JSON. Stringify
-
Object.keys( )
1, for… In traverses object properties
let obj = {};
for (var i in obj) {// If the object is not empty, it will be executed here, returning true
return true
}
return false// Return false if the object is empty
}
Copy the code
2. Use json.stringify
let obj = {};
if (JSON.stringify(obj) === "{}") {
return false
}
return true // Non-empty object, return true
Copy the code
3, the Object. The keys ()
ES5 introduced the Object.keys method, which returns an array of all the key names of the parameter Object’s own (not inherited) Enumerable properties.
let obj = {};
console.log(Object.keys(obj));/ / []
var obj = { foo: 'bar'.baz: 42 };
console.log(Object.keys(obj));//["foo", "baz"]
Copy the code
We can tell if the returned data is empty by judging its length:
let obj = {};
if (Object.keys(obj).length === 0) {
console.log("Empty object");
return false
}
return true
Copy the code
Keys () :
References:
- Describe the difference between Typeof and Instanceof
- ES6- New Object method object.keys