The main content of this article is to comb through JavaScript and summarize some front-end basic knowledge, so make a record.

The data type

JavaScript data types are divided into basic data type \textrm\color{red}{basic data type} basic data type and reference data type \textrm\color{red}{reference data type} reference data type

Basic data type

There are currently 7\textrm\color{red}{7}7 basic data types;

  • Null
  • Undefined
  • Number
  • Boolean
  • String
  • Symbol (es6)
  • Bigint (es10)

Reference data type

In JavaScript, {color}{color}{color}{color}{color}{color}{color}{color}{color} Are object types

  • Object

Stack and data storage

The data stack

In JavaScript, every piece of data needs to have its corresponding memory space. There are two main types of memory: stack memory and heap memory.

  • Basic data types are stored in stack memory because of their small footprint, fixed storage size, and high efficiency.
  • Reference data types are stored in heap memory because they take up large space, have variable storage sizes, and run less efficiently than stack memory.
var a = 'abc'
var b = 10
var person = {
  name : 'xiaoming'.age : 18} As shown in the example, variables a and b are basic data types, stored in stack memory. The person variable is a reference type, and its value is stored in heap memory, and its application address is stored in stack memory to reference the object.Copy the code

Assignment and passing

Copying a value from one variable to another is different from copying a value from a reference to a data type because of the differences in the way that basic data types are stored and referenced.

  • For values of basic data types, we always assign and pass values by copying values.
  • For reference data types, we always assign and pass by reference copy.
   var a = 'abc'
   var b = 10
   var c = b
   b = 11
   console.log(a,b,c)   // abc 11 10

   var person = {
     age : 18
   }
   var person1 = person
   person.age = 81
   console.log(person.age, person1.age)   / / 81 81As the example shows:10B holds a copy of this value. When we assign the value of b to c, we actually create a new stack memory space for c, and c also holds a copy of the value. The two variables point to completely independent memory space and do not affect each other. Person is a reference data type whose value is stored in heap memory, and when we assign the variable Person to Person1, we are actually copying the reference address of Person, in which case person and Person1 both point to the same heap memory space. When the code executes person.age =81, actually changes the value in the heap that the address points to, so the value of the output person also changes.Copy the code

Data type determination

In Javascript, we determine the data type of commonly used there are three ways of typeof instanceof Object. The prototype. ToString. Call ()

typeof

Typeof \textrm\color{red}{typeof}typeof \textrm\color{red}{object}object; Null \textrm\color{red}{null} NULL is a historical issue.

    typeof '123'        // string
    typeof 123          // number
    typeof true         // boolean
    typeof undefined    // undefined
    typeof Symbol(1)     // symbol
    typeof BigInt(1)     // bigint

    typeof Function     // function
    typeof null         // object
    typeof []           // object
    typeof {}           // object
    typeof new Date(a)// object
Copy the code

instanceof

Instanceof \textrm\color{red}{instanceof}instanceof is usually used to determine whether a variable is an instanceof an object by looking up __proto__. Can you find the prototype object to which the constructor’s prototype refers?).

[] instanceof Array // true [] instanceof Object // true {} instanceof Object // true null instanceof Object // true new  Date() instanceof Object // true function Person(){} new Person() instanceof Person // trueCopy the code

Object.prototype.toString.call

Object. The prototype. ToString. Call \ textrm \ color {red} {Object. The prototype. ToString. Call} Object. The prototype. ToString. The call is usually used to judge JS native If the toString method is not overridden, it returns [Object type], where type is the type of the Object.

    1, determine the basic typeObject.prototype.toString.call("String")         // "[object String]"
      Object.prototype.toString.call(1)               // "[object Number]"
      Object.prototype.toString.call(Symbol(1))       // "[object Symbol]"
      Object.prototype.toString.call(null)            // "[object Null]"
      Object.prototype.toString.call(undefined)       // "[object Undefined]"
      Object.prototype.toString.call(true)            // "[object Boolean]"
      Object.prototype.toString.call(BigInt(1))       // "[object BigInt]"

    2, determine the native reference typeObject.prototype.toString.call(function(){})    // "[object Function]"
      Object.prototype.toString.call(new Date())      // "[object Date]"
      Object.prototype.toString.call([])              // "[object Array]".3, determine non-native objectsfunction Person(person) {
          this.name = person.name
          this.age = person.age
      }
      const person = new Person({age:18.name:'aa'})
      Object.prototype.toString.call(person)  // "[object Object]"
      Object.prototype.tostring. call Is not recommended to use this method to determine whether a person is an instance object of the Person classinstanceofTo judgeCopy the code

constructor

Constructor \textrm\color{red}{constructor}constructor can be used to check javascript’s basic data types as well as reference data types, provided that the prototype of the reference type cannot be modified.

    "1".constructor === String              // true
    (1).constructor === Number              // true
    (false).constructor === Boolean         // true
    (new Date()).constructor === Date       // true
    ({name:'test'}).constructor === Object  // true
    (function(){}).constructor === Function // true
    ([]).constructor === Array              // true

    // Constructor cannot properly check the data type after changing the prototype
    function Person(person) {
        this.name = person.name
        this.age = person.age
    }
    new Person({age:18.name:'aa'}).constructor === Person   // true
    
    function Creature(){}
    Person.prototype = new Creature()
    new Person({age:18.name:'aa'}).constructor === Creature // true
Copy the code

Data type conversion

Explicit type conversion

To manually convert data types, use the following conversion functions:

  • String type: String (Object), the toString (radix) \ textrm \ color {red} {String (Object), the toString (radix)} String (Object), the toString (radix)
  • Value type: Number (Object), parseInt (string, radix), parseFloat (string) \ textrm \ color {red} {Number (Object), the parseInt (string, ParseInt (string, radix), parseFloat(string, Radix), parseFloat(string, Radix)
  • Type: Boolean(object) \textrm\color{red}{Boolean(object)}Boolean(object)

ToString (RADIX)\textrm\color{red}{toString(radix)}toString(Radix)\textrm\color{red}{toString(Radix)}toString(Radix)

  • In Javascript, all types of values except undefined and NULL have a toString() method.
    object The results of
    String Returns the corresponding string
    Number Returns a string of numbers
    Boolean Return “true” if Boolean is true, and “false” otherwise.
    Function Function test() {[native code]}
    Array [1,2,3] == “1,2,3”
    Date Returns a string of readable standard dates and times
    RegExp Returns a string that is a direct part of a regular expression
    Error Returns a string containing the relevant error information

String(mix)\textrm\color{red}{String(mix)}String(mix)

  • If mix is null, return the string “null”
  • If mix is undefined, return the string “undefined”
  • If the object has a toString(), call the toString method and return the original value, which Javascript converts to a string; If the object does not have a toString method, and the return value is not the original value, then the valueOf method is called, converting and returning according to the previous rule; If toString or valueOf fails to return the original value, Javascript throws an exception. Note: All types of values except undefined and NULL have a toString() method.
  • The date object is converted to a string directly by calling toString(), without calling valueOf


Number(mix) \textrm\color{red}{Number(mix)}

  • If mix is of type Boolean, true returns 1 and false returns 0
  • If mix is of type Number, it returns itself
  • If mix is undefined, then NaN is returned
  • If mix is a pure numeric string, the number is returned
  • If min is an empty array, 0 is returned
  • If mix is an empty string, 0 is returned
  • If mix is a non-numeric, empty string, then NaN is returned
  • If minx is an object and the object has a valueOf method, this method is called; If not, the toString method is called, which follows the previous rule and returns; Otherwise Javascript throws an exception.


parseInt(string, radix) \textrm\color{red}{parseInt(string, radix)}

  • ParseInt () ignores Spaces before a string, and returns NaN if the string is not a numeric character or a negative sign.
  • ParseInt () parses a string from the first character until a non-numeric character is encountered or parses are complete. For example, “123abc” returns 123. ABC is ignored. “12.5” will return 12 and.5 will be ignored.
  • When the radix value is 0, or the parameter is not set, parseInt() will judge the radix of the number based on the string. If the string starts with “0x” followed by a numeric character, it will be treated as a hexadecimal integer; If the string starts with “0” and is followed by a numeric character, it is parsed as an octal number (less than ECMAScript 5) or decimal, depending on the ES version.


parseFloat(string) \textrm\color{red}{parseFloat(string)}

  • ParseFloat () ignores the space before the string, and returns NaN if the string is not a numeric character or a negative sign.
  • ParseFloat () parses from the first string character until a non-numeric character is encountered or parsing is complete, and returns the successfully parsed numeric character. The first decimal point in the string string is valid
  • Parse only decimal data


Boolean(object) \textrm\color{red}{Boolean(object)}

  • False: false, 0, NaN, NULL, undefined, “”
  • Everything else is true

Implicit type conversion

In JS, when the operator is in the operation, if the two sides of the data type is not uniform, Javascript compiler will automatically do a data type conversion on both sides of the operator, into the same data type and then calculate; The way that the compiler automatically converts without manual conversion is called implicit conversion.

  • Arithmetic operators: + (plus) – (subtraction) * (multiplication)/(division) % (yu) + + (increasing) — – (decreasing) \ textrm \ color {red} {+ (plus) – (subtraction) * (multiplication)/(division) \ % (yu) + + (increasing) — – (decreasing)} +(add)-(subtract)*(multiply)/(divide)%(mod)++(increase)- -(decrease)

    • “++”, “–“, “/”, “%”, “*” conversion rules
      1. If the operand is not of numeric type, then the Number() function is implicitly called to perform the conversion
      2. If the operand cannot be converted to a numeric type, set the value of the operand to NaN
    • The “+” addition operator converts rules
      1. If both operands are strings, concatenate the string
      2. If one of the two operands is a string, concatenation is performed by converting the other operands to a string
      3. If both operands are numbers, the arithmetic addition is performed
      4. If the two operands are neither strings nor numbers, then the Number() function is implicitly called to convert and then evaluate
  • Comparison operators: > (greater than), < (less than) > = (greater than or equal to) < = (less than or equal to) \ textrm \ color {red} {> (greater than), < (less than) > = (greater than or equal to) < = (less than or equal to)} > (greater than), < (less than) > = (greater than or equal to) < = (less than or equal to)

    1. If both operands are of numeric type, a numeric comparison is performed
    2. If both operands are strings, the character encoded value of the string is converted to a number and then compared
    3. If one of the operands is of numeric type, the other operand is converted to numeric type for comparison
    4. If one of the operands is a Boolean type, the conversion to a numeric type is compared according to the above rules
    5. If the operand is an object, the valueOf() conversion is called first according to the object conversion rules. If the result returned by valueOf() is the original value, the returned data is used for comparison. Otherwise, the result returned by the call to toString () is compared
    6. NaN cannot be compared with any operand, including NaN
     /* If one of the operands is of numeric type, convert the other operand to numeric type and compare * 1, Number(true) = 1, * 2, 1 >= 1 returns true */
      console.log(1> =true) // true
    
      /* If one of the operands is numeric, compare the other to numeric * 1, Number("0") = 0, * 2, 1 >= 0 returns true */
      console.log(1> ="0") // true
    
      /* If one of the operands is of numeric type, convert the other operand to numeric type and compare * 1, Number(null) = 0, * 2, 1 >= 0 returns true */
      console.log(1> =null) // true
      
      /* NaN cannot be compared with any operands, Return false * 1, {}.valueof ().toString() returns "[object object]" * 2, Number("[object object]") = NaN, * 3, 1 >= NaN returns false */
      console.log(1> = {})// false
    Copy the code
  • Equality and inequality operators: ==! = \ textrm \ color {red} {= =! =} = =! =

    1. If one of the operands is of numeric type, the comparison is converted by implicitly calling the Number() function
    2. If one of the operands is a Boolean, the Boolean is converted to number and then compared
    3. If one of the operands is of an object type, then valueOf() is called and the results returned are compared according to the previous rule
    4. Null and undefined are equal
    5. If one of the operands is equal to NaN, the comparison returns false
    6. If both operands are objects, the comparison is whether they refer to the same instance object
  • Logical non-operator:! \textrm\color{red}{! }!

    1. Convert other data types to Boolean values using the Boolean() function
    2. All conversions return true except for 0, -0, NaN, undefined, NULL, “”, false, document.all()
    /* Rationale * 1, [].valueof ().toString() returns "" empty string, * 2, then Number("") returns 0 * 3, 0 == 0 returns true */
    console.log([] == 0) // true
    
      }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} False * 3, Number(false) = 0 * 4, 0 == 0 return true */
    console.log(! [] = =0) // true
    
     [].valueof ().toString() returns "" an empty string, * 2,! [] = false * 3, Number("") = 0 * 4, Number(false) = 0 * 5, 0 == 0 return true */
    console.log([] == ! [])// true
    
    Return false */ 1. The value of the reference data type is stored in the heap. The stack contains the address of the reference, so return false */
    console.log({} == {}) // false
    
    {}.valueof ().toString() returns "[object object]"; {} = false * 3, Number("[object object]") = NaN * 4, Number(false) = 0 * 5, NaN == 0 return false */
    console.log({} == ! {})// true
    
    Copy the code