js data type sorting, detection and conversion

Data type sorting

js data types are 8
Basic type undefined,Null,Boolean,String,Number,Symbol,BigInt
The reference data type is Object, and the common reference types are array, regexp, date, math and function.

  1. The basic data type is stored in the stack memory. When it is referenced or copied, it will create variables that are exactly equal to the moth
  2. The reference type is stored in the heap memory. It stores addresses. Multiple references point to the same address and are in the "shared" state.

An object + function example

let a = {
    nae:'jake',
    age:18
}

function change (e){
    e.age = 20
    e = {
        name :'tom',
        age:30
    }
    return e
}
let b  = change(a);
console.log(b.age)
console.log(a.age)

The print result is

30
20

The first line of code in function changes the age attribute of object a, but return e returns the address of the new object e={name:'tom',age:30} to b. If function does not return, the first line will print and prompt undefined

Data type detection

The first detection method is typeof

typeof 1 // 'number'
typeof '1' // 'string'
typeof undefined // 'undefined'
typeof true // 'boolean'
typeof Symbol() // 'symbol'
typeof null // 'object',js legacy BUG, does not mean null. It is a reference data type and not an object
typeof [] // 'object'
typeof {} // 'object'
typeof console // 'object'
typeof console.log // 'function'

The second detection method is instanceof

let Human = function(){};
let women = new Human()
console.log(women instanceof Human) // true
let man  = new String("Human");
console.log(man instanceof String) // true
let str = "abc";
console.log(str instanceof String) // false

According to the existing features of instanceof, a myinstanceof is implemented

function myinstanceof(val,typeName) {
    if(typeof val  !== 'object' || val === null) return false
    // getPrototypeOf is used to get the parameter prototype object
    let proto = Object.getPrototypeOf(val);
    while(true){
        if(proto === null)  return false;
        if( proto === typeName.prototype) return true;
        proto = Object.getPrototypeOf(proto)
    }
}

console.log(myinstanceof('123',String))  // false
console.log(myinstanceof(new String('123'),String))  // true

From the above, we know that there are problems in the two methods of judging types: typeof and instanceof

  1. instanceof can accurately judge complex reference data types, but it cannot correctly judge basic data types;
  2. typeof can judge the basic data type (except null), but in the reference data type, other types can not be judged except function type

The third detection method is object prototype. toString

Object.prototype.toString({})       // "[object Object]"
Object.prototype.toString.call({})  // "[object Object]"
Object.prototype.toString.call(1)    // "[object Number]"
Object.prototype.toString.call('1')  // "[object String]"
Object.prototype.toString.call(true)  // "[object Boolean]"
Object.prototype.toString.call(function(){})  // "[object Function]"
Object.prototype.toString.call(null)   //"[object Null]"
Object.prototype.toString.call(undefined) //"[object Undefined]"
Object.prototype.toString.call(/123/g)    //"[object RegExp]"
Object.prototype.toString.call(new Date()) //"[object Date]"
Object.prototype.toString.call([])       //"[object Array]"
Object.prototype.toString.call(document)  //"[object HTMLDocument]"
Object.prototype.toString.call(window)   //"[object Window]"

Based on the characteristics of basic sub methods, a method to obtain data types can be implemented

function getType(val) {
    let type = typeof val;
    // Direct return of basic data type
    if (type !== "object")
        return type
    // object
    return Object.prototype.toString.call(obj).replace(/^\[object (\S+)\]$/, '$1');  // Notice a space in the middle of the regular
}

Type conversion rules

Cast rule for Number() method

  1. If it is a Boolean value, true and false are converted to 1 and 0 respectively;
  2. If it is a number, return itself;
  3. If null, return 0;
  4. If undefined, NaN is returned;
  5. If it is a string, follow the following rules: if the string contains only numbers (or hexadecimal digit string starting with 0X / 0x, positive and negative signs are allowed), convert it to decimal; If the string contains valid floating-point format, convert it to floating-point value; If it is an empty string, convert it to 0; If the string is not in the above format, NaN is returned;
  6. If it is a Symbol, an error is thrown;
  7. If it is an Object and [Symbol.toPrimitive] is deployed, call this method; otherwise, call the valueOf() method of the Object, and then convert the returned value according to the previous rules; If the result of the conversion is NaN, call the toString() method of the Object and convert again in the previous order to return the corresponding value (the Object conversion rules will be described in detail below).
Number(true);        // 1
Number(false);       // 0
Number('0111');      //111
Number(null);        //0
Number('');          //0
Number('1a');        //NaN
Number(-0X11);       //-17
Number('0X11')       //17

Cast rule for Boolean() method
Rule: all are true except undefined, null, false, '', 0 (including + 0, - 0) and NaN converted to false.

Implicit type conversion

Through logical operators (& &, |,!) Implicit type conversion will occur for operators (+, -, *, /), relational operators (>, <, < =, > =), equality operators (= =) or if/while conditions
Implicit type conversion rule for '= ='

  1. If the types are the same, no type conversion is required;
  2. If one of the operation values is null or undefined, the other operator must be null or undefined to return true, otherwise it will return false;
  3. If one of them is of Symbol type, false is returned;
  4. If the two operation values are of type string and number, the string will be converted to number;
  5. If an operation value is boolean, it is converted to number;
  6. If an operation value is object and the other party is string, number or symbol, the object will be converted to the original type for judgment (call the valueOf/toString method of object for conversion).

Implicit type conversion rule for '+'

  1. The '+' operator can be used not only as a number addition, but also as a string splicing. Only when both sides of the '+' sign are numbers, the addition operation is performed; If both sides are strings, they are spliced directly without implicit type conversion.
  2. If one of them is a string and the other is undefined, null or boolean, call the toString() method for string splicing; If it is a pure object, array, regular, etc., the conversion method of the calling object will have priority by default (which will be specifically introduced in the next lecture), and then splicing.
  3. If one of them is a number and the other is undefined, null, Boolean or number, it will be converted into a number for addition. For the object, refer to the previous rule.
  4. If one of them is a string and the other is a number, they are spliced according to the string rules.

Object conversion rules
For the rule of object conversion, the built-in [ToPrimitive] function will be called first. The rule logic is as follows:

  1. If symbol. Is deployed Toprimitive method, call first and then return;
  2. Call valueOf(). If it is converted to a basic type, it returns;
  3. Call toString(). If it is converted to a basic type, it returns;
  4. If no basic type is returned, an error will be reported.

Keywords: Javascript Front-end ECMAScript

Added by djcubez on Sat, 11 Dec 2021 10:23:01 +0200