Summary of Vue front-end interview questions (2) Detailed data type judgment

Data type judgment

Our common data types There are two
basic types of data and reference data types
basic data types

  1. Number

  2. String

  3. Null

  4. Boolean

  5. undefined

  6. Symbol (new in ES6)

Reference data type

1.Object
2.Array
3.Date
4.Function
5.Error
6.RegExp
7.Math
8.Number
9.String
10.Boolean
11.Globle。

There are generally four ways to judge data

typeof
instanceof
constructor
Object.prototype.toString.call()

Let's talk about

1、typeof

It can judge the basic data type, the string of the data type it returns
(the returned result can only include number , boolean , string , function , object , undefined )
but it cannot judge null and array. You can use typeof to judge whether the variable exists (such as if( typeof a!=“undefined”){…}); But for some created objects, they will return a simple example of'object'

console.log(typeof a);    //'undefined'
console.log(typeof (true));  //'boolean'
console.log(typeof '123');  //'string'

2、Instanceof

Judging the reference data type is used to test whether an object has a constructor prototype property in the prototype chain, but it cannot detect null and undefined (Instanceof is not a function, it is an operator)
to determine whether A is an instance of B, A instanceof B, returns the boolean value.
Instanceof detects the prototype
code implementation:

function Student() {
    
    

}
var a = new Student()
console.log(a instanceof Student)  //返回true

3、constructor

In addition to undefined and null, other types can be judged by the constructor attribute, which seems to be able to deal with basic data types and reference data types, but if a constructor is declared and its prototype point is changed, this situation Next, the constructor will not work.
Code:

var str = ""
console.log(str.constructor) //输出结果String

4、Object.prototype.toString.call()

Code

var date = newDate();
Object.prototype.toString.call(date); // "[object Date]"
Object.prototype.toString.call(true);// "[object Boolean]"

Determine which built-in type an object value belongs to. Cannot accurately determine whether an instance belongs to a certain type.
Implementation: Return the type string of the object, which can be used to determine the type of a value

Principle: Since the instance object may customize the toString method and override the Object.prototype.toString method, in order to obtain the type string, it is best to directly use the Object.prototype.toString method. Through the call method of the function, this method can be called on any value to help us determine the type of this value.

Guess you like

Origin blog.csdn.net/Rick_and_mode/article/details/108600279