I. Type detection

1. The typeof method

Typeof is an operator that can be used in two ways: typeof(expressions) and Typeof variable names, the first to operate on expressions and the second to operate on variables. The typeof operator returns the following values:

  • ‘undefined’ — undefined variable or value
  • ‘Boolean’ — Boolean type variable or value
  • ‘String’ – a variable or value of type string
  • ‘number’ – variable or value of type number
  • ‘object’ — a variable or value of the object type, or NULL (this is a legacy of JS history, treating null as an object type since design timenullIs all zeros, and the object is000At the beginning, hence the miscarriage of justice)
  • ‘function’ – a variable or value of function type

Simple example

    console.log(typeof a);    //'undefined'
    console.log(typeof(true));  //'boolean'
    console.log(typeof '123');  //'string'
    console.log(typeof 123);   //'number'
    console.log(typeof NaN);   //'number'
    console.log(typeof null);  //'object'    
    var obj = new String(a);console.log(typeof(obj));    //'object'
    var  fn = function(){};
    console.log(typeof(fn));  //'function'
    console.log(typeof(class c{}));  //'function'
    console.log(typeof([]));  //'object'
Copy the code

Note: typeof checks return only strings, so

    typeof(typeof(11));         //"string"
Copy the code

In addition:

typeof(null) =Object  
typeof(Object) =function// All built-in constructors are of typefunction
Copy the code

2. The instance of method

When typeof detects a variable of type Object, it cannot further detect what typeof Object it is (e.g. Array,Date).

Instanceof is used to determine if a variable is an instanceof an object. For example:

console.log([] instanceof Array);//true
console.log({} instanceof Object);//true
console.log(/\d/ instanceof RegExp);//true
console.log(function(){} instanceof Object);//true
console.log(function(){} instanceof Function);//true
Copy the code

However, it does not determine the underlying data type of JS

console.log(' ' instanceof String);//false
console.log(1 instanceof Number);//false
Copy the code

In addition, instanceof is most useful for detecting custom classes, and since the internal mechanism is that Instanceof determines the type by determining whether the right constructor’s prototype exists in the left object’s prototype, it can also detect inheritance relationships

The general situation

function User(name){this.name = name}
var user = new User()
user instanceof User    //true
Copy the code

There is also the case of inheritance

function Foo() {{
	this.name = 'wyh'
	this.age = '23'
}

function GFoo() {
	this.country = 'China'
}

Foo.prototype = new GFoo()

let foo = new Foo()
console.log(foo instanceof Foo)  // true
console.log(foo instanceof GFoo) // true}}

Copy the code

3. The use of the Object. The prototype. ToString. Call ()

Calls to the Object. The prototype. ToString. Call () method can determine a variable belong to which kinds of js’s built-in objects, and the output standard format.

Basic type of detection

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]"
Copy the code

Detecting reference types

Function fn(){
  console.log (" test "); }Object.prototype.toString.call(fn); // "[object Function]"

var date = new Date(a);Object.prototype.toString.call(date); // "[object Date]"

var arr = [1.2.3];
Object.prototype.toString.call(arr); // "[object Array]"

var reg = /[hbc]at/gi;
Object.prototype.toString.call(reg); // "[object RegExp]"

Copy the code

Note: Custom types cannot be detected

function Person(name, age) {
    this.name = name;
    this.age = age;
}
var person = new Person("Rose".18);
Object.prototype.toString.call(arr); // "[object Object]"
Copy the code

4. Implement a type judgment function

Ideas:

  1. Determine the null
  2. Use Typeof to determine the underlying type
  3. useObject.prototype.toString.call(target)To judgeReference types

Type conversion

1. Explicit type conversion

The Number () function

The Number function converts the contents of the parentheses directly to a Number of type Number, and returns a NaN instead of an error if it cannot convert.

Note: Converting null to a number returns 0, and converting undefined to a number returns NaN

Number("123")   / / 123
Number('abc')  //NaN
Number(null)   / / 0
Number(underfined) //NaN
Copy the code

String () function

The String function, like Number, converts the contents of the parentheses directly to a String.

Notice that

  • When a value such as null undefined is converted, both “null” and “undefined” are returned as strings.
  • When converting floating point numbers like 1.00 and 1.10, zeros are automatically eliminated
String(999)   / / "999"
String(null)  //'null'
String(undefined)   //"undefined"
String(1.00)  / / 1
Copy the code

The parseInt () function

This function converts the value inside the parentheses to an integer. The second argument can be received, which is the base type of the number being converted

But be warned

  • Using this function to convert values like ‘123abc’ does not return an error, but the number 123 is returned. This is because the function stops at the first non-numeric bit by default.
  • When converting a floating point number, only the integer part is preserved.
  • A NaN is returned for variable functions that cannot be converted at all.
parseInt('16'.8) //14 converts base 16 to base 10
parseInt("11aaa")   / / 11
parseInt("aaa11")   //NaN
parseInt('1.23 ABC') / / 1
parseInt('1.23')    / / 1
Copy the code

The parseFloat () function

This function has almost the same characteristics as ParseInt(), except that it can convert not only integers but also floating-point numbers.

console.log(parseFloat("123"));         / / 123
console.log(parseFloat("123.123"));     / / 123.123
console.log(parseFloat("123.00"));      / / 123
console.log(parseFloat("123.12 aaa31")); / / 123.12
console.log(parseFloat("aaa123.1231")); //NaN
console.log(parseFloat("aaa"));         //NaN
Copy the code

The toString () method

This method is similar to String(), but with two differences,

  • One is that this method is called by adding.toString to the end of the variable
  • One is that this method can’t convert null and undefined
var a = 123
console.log(a.toString());  / / "123"
var b;      
console.log(b.toString());  / / "error"
var c = null;
console.log(c.toString());  / / "error"
Copy the code

Boolean () method

This method converts the contents of the parentheses to a Boolean value, and returns true for any converted object.

console.log(Boolean(1));            //true
console.log(Boolean(0));            //false
console.log(Boolean(""));           //false
console.log(Boolean(undefined));    //false
console.log(Boolean([]));           //true
console.log(Boolean({}));           //true
Copy the code

Implicit type conversion

isNaN()

It determines whether a variable is NaN, but it does a type conversion by first converting the contents in parentheses to Number.

Finally, anything that can’t be converted to Number will return false, so it can’t explicitly determine if a variable is a NaN

IsNaN (123) returns false isNaN(' ABC ') // Returns true isNaN(undefined) // Returns true isNaN(null) // Returns false isNaN(NaN) // Returns trueCopy the code

++/– +/- one dollar plus or minus

Number() is called for type conversion, followed by operator operations on variables

++ '123'  // Return 124 of type number
++ 'abc' // Return NaN of type number
Copy the code

The addition operator: +

When there is a String on either side of the operator, the implicit method called is String()

123+"aaa"
//"123aaa"
123+"111"
/ / "123111"
Copy the code

Other operators: – * / %

The Number() type conversion is performed on the variables on either side of the operator, and then the operation is performed

"a" - 1  // The result is NaN
1 * 'a'  // The result is NaN
Copy the code

With or not: && | |!

The Boolean() method is used to implicitly cast both sides of an expression

Comparison operators: > >= < <=

If one of the two is not a number, it is first converted to a number (true to 1, false to 0) and then compared to return a Boolean value.

Is equal to: = =

This comparison first converts both sides to the same type and then compares their values for equality, noting that NaN==NaN returns false

3. Packing conversion and unpacking conversion

Boxing conversion: The operation of converting a base data type to a corresponding reference data type

Every time a primitive type is read, a corresponding primitive wrapper type object is created behind the scenes, allowing us to call methods to manipulate the data.

Such as

var s1 = "abc";
var s2 = s1.indexOf("a")
Copy the code

S1 is a primitive type value, it is not an object, and it should not have methods. But internally, JS does a bunch of processing (i.e. boxing) for us, so that it can call methods. The mechanism is as follows:

  • Create an instance of String.
  • Invokes the specified method on the instance.
  • Destroy the instance;

The following operations are implicitly performed in the background

var s1  = new String("some text");
var s2 = s1.substring(2);
s1 = null;
Copy the code

This completes the boxing, and we can call the method on S1

Unboxing conversion: Converts a reference type object to the corresponding value type object

It is implemented through valueOf() or toString() methods of reference types. If it is a custom object, you can also customize its valueOf()/ toString () methods to unbox the object

Such as

var num = new Number(10);
console.log(typeof(num));   //Object
num = num + 2;
console.log(typeof(num));   //Number


var o = {
	valueOf: () = > { console.log("valueOf"); return 1 },
	toString: () = > { console.log("toString"); return 1}}console.log(o + "aaa"); // "1aaa"
console.log(o * 2);     / / 2
Copy the code

Note: Normally it calls your valueOf method first, and toString method only if it doesn’t exist.


The last

Thank you for reading this, feel free to leave a comment in the comments section, and if you can, just click “like” before you leave.