5 basic reference type

Posted by majik-sheff on Tue, 04 Jan 2022 22:23:28 +0100

Basic reference type

  1. Date date is saved as the number of milliseconds since zero o'clock on January 1, 1970 UTC.

    1. Date. The parse () method receives a string parameter representing the date and attempts to convert the string to the number of milliseconds representing the date. All implementations must support the following formats

      1. Month / day / year, such as "May 23 / 2019"
      2. Month name day, year, such as "may 232019"
      3. Day of the week month name day year hour: minute: second time zone, such as "Tue May 23 2019 00:00:00 GMT-0700"
      4. YYYY-MM-DDTHH:mm:ss:sssZ, such as "2019-05-23T00:00:00"

      If the string passed to the method does not represent a date, NaN is returned

      let someDate = new Date(Date.parse("May 23,2019"))
      // The above code is equivalent to the following code, and date will be called in the background parse
      let someDate = new Date("May 23,2019")
      
    2. Date. The parameters received by UTC () are year, zero starting month (January is 0, February is 1, and so on), day (131), hour (023), minute, second and millisecond. Of these parameters, only the first two (year and month) are required. If no day is provided, it defaults to 1 day. The default value of other parameters is 0

      // 00:00 GMT, January 1, 2000
      let y2k = new Date(Date.UTC(2000, 0)); 
      // 5:55:55 pm GMT 05 / 05 / 2005
      let allFives = new Date(Date.UTC(2005, 4, 5, 17, 55, 55));
      

      The creation date of the above code is the date of the local time zone determined by the system setting.

    3. Date. The now () method returns the number of milliseconds representing the date and time when the method was executed.

      // Start time
      let start = Date.now()
      // Call function
      doSomething()
      // End time
      let stop = Date.now()
      result = stop - start
      
    4. The toString() method returns the date and time with time zone information, and the toLocaleString() returns the time and date consistent with the local environment in which the browser runs

      let now = new Date()
      console.log(now)//Thu Dec 23 2021 16:14:39 GMT+0800 (China standard time)
      console.log(now.toString())//Thu Dec 23 2021 16:14:39 GMT+0800 (China standard time)
      console.log(now.toLocaleString())//4:14:39 pm on December 23, 2021
      
    5. The valueOf() method returns the millisecond display of the date, so the operator can directly use its returned value for calculation, etc

  2. RegExp regular expression, whose pattern can be any simple or complex regular expression, including character class, qualifier, grouping, forward lookup and back reference. Each regular expression can take zero or more flags, or tags, to control the behavior of the regular expression

    1. g: Global mode to find all the contents of the string
    2. i: Case insensitive, ignoring the case of pattern and string
    3. m: Multiline mode
    4. y: Glue mode, which only finds strings starting from and after lastIndex
    5. u: Unicode mode
    6. s: dotAll mode, representing metacharacters, matching any character (including \ n or \ r)
    // Match all "at" in the string
    let pattern1 = /at/g
    // Match the first "bat" or "cat", ignoring case
    let pattern2 = /[bc]at/i
    // Matches all three character combinations ending with "at", ignoring case
    let pattern3 = /.at/gi
    

    All metacharacters must also be escaped in the mode, including ([{\ ^ $|]}? * +

    let pattern1 = /[bc]at/i; 
    // Match the first '[bc]at', ignoring case
    let pattern2 = /\[bc\]at/i; 
    // Matches all three character combinations ending with "at", ignoring case
    let pattern3 = /.at/gi; 
    // Match all ". at", ignoring case
    let pattern4 = /\.at/gi;
    

    Among them Indicates that any preceding character can be matched, [] indicates one of them. Regular expressions can be created using the RegExp constructor and receive two parameters: the pattern string and the tag string:

    // Match the first "bat" or "cat", ignoring case
    let pattern1 = /[bc]at/i
    // Like pattern1, it's just created with a constructor
    let pattern2 = new RegExp("[bc]at", "i")
    

    The mode parameter of RegExp is a string. In some cases, secondary escape is required:

    [the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-wb6tqz9s-16412937955) (C: \ users \ czhho \ appdata \ roaming \ typora user images \ 1640249337349. PNG)]

    [the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-8xhxcte1-16412937955) (C: \ users \ czhho \ appdata \ roaming \ typora user images \ 1640249528612. PNG)]

    let pattern1 = /\[bc\]at/i; 
    console.log(pattern1.global); // false 
    console.log(pattern1.ignoreCase); // true 
    console.log(pattern1.multiline); // false 
    console.log(pattern1.lastIndex); // 0 
    console.log(pattern1.source); // "\[bc\]at" 
    console.log(pattern1.flags); // "i" 
    let pattern2 = new RegExp("\\[bc\\]at", "i"); 
    console.log(pattern2.global); // false 
    console.log(pattern2.ignoreCase); // true 
    console.log(pattern2.multiline); // false 
    console.log(pattern2.lastIndex); // 0 
    console.log(pattern2.source); // "\[bc\]at" 
    console.log(pattern2.flags); // "i"
    

    The main method of RegExp instance is exec(), which is used in conjunction with the capture group to receive only the string to which the pattern is to be applied. If a matching item is found, the Array containing the first matching information is returned; if it is not found, null is returned; The returned Array instance contains two additional attributes. index is the starting position matched in the string, and input is the string to be found. The first element of the Array is the string matching the whole pattern, and other elements are the string matching the capture group in the expression. If there is no capture group, the Array contains only one element

    let str = "mom and dady and baby"
    let str1 = "hingfiad ans dsd"
    let str2 = "mom and asdi sad"
    let str3 = "mom and "
    let str4 = " and baby"
    let str5 = "joadjisa sada and dady and baby"
    let rule = /mom( and dady( and baby)?)?/gi
    
    let match = rule.exec(str)
    let match1 = rule.exec(str1)
    let match2 = rule.exec(str2)
    let match3 = rule.exec(str3)
    let match4 = rule.exec(str4)
    let match5 = rule.exec(str5)
    console.log(match)
    console.log(match1)
    console.log(match2)
    console.log(match3)
    console.log(match4)
    console.log(match5)
    

    [the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-kfv45vgi-16412937956) (C: \ users \ czhho \ appdata \ roaming \ typora user images \ 1640258372133. PNG)]

    [the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-nchf70aj-16412937956) (C: \ users \ czhho \ appdata \ roaming \ typora user images \ 16402583827. PNG)]

    If the g flag is set on the pattern, the next match is searched forward in the string after each call to exec

    RegExp static properties

    [the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-khzlgfaq-16412937957) (C: \ users \ czhho \ appdata \ roaming \ typora user images \ 1640259154398. PNG)]

    Capture group and non capture group

    regular expression

    let str = 'sq0000.'
    str1 = str.replace(/(sq000)0./,'$1g')
    str2 = str.replace(/(sq000)(?:0)/,'$1g')
    str3 = str.replace(/(sq000)(0.)/,'$1g,$2g')
    str4 = str.replace(/(sq000)(?:0)/,'$1g,$2g')
    console.log(str)
    console.log(str1)
    console.log(str2)
    console.log(str3)
    console.log(str4)
    /**
     * sq0000.
     * sq000g
     * sq000g.
     * sq000g,0.g
     * sq000g,$2g.
     */
    
  3. Whenever a string value is accessed in read mode, the following steps are performed in the background

    1. Create an instance of String type
    2. Calling a specific method on an instance
    3. Destroy instance
    let s1 = "some text"
    let s2 = s1.substring(2)
    // Actually equivalent to
    let s1 = new String("some text")
    let s2 = s1.substring(2)
    s1 = null
    

    **This also happens for Boolean and Number values** However, the automatically created original value wrapper Object only exists during the execution of the line of code accessing it, that is, you can no longer add properties and methods to the original value at run time. As a factory method, the Object constructor can return an instance of the corresponding original value wrapper type according to the type of the incoming value.

  4. The difference and relation between slice substr substring

    1. The three accept two parameters, the first is the position index of the first character intercepted, and the second is the end position; The second parameter of substr gets the number of substrings.
    2. When there are negative numbers in the passed in value, slice interprets all negative values as string length plus negative parameter value; substr interprets the first parameter as slice, and if the second parameter is negative, it is understood as 0, that is, the length of the string to be output is 0, so the output is an empty string; substring understands the negative numbers entered as 0. In this parameter, the smaller of the two parameters passed in is actually used as the start index and the larger as the end index;
    let str = "Hello World!"
    console.log(str.slice(1,4))       //"ell"
    console.log(str.substring(1,4))   //"ell" 
    console.log(str.substr(1,4))      //"ello"
    
    console.log(str.slice(-3))        //"ld!"
    console.log(str.substring(-3))    //"Hello World!"  Since the passed in is a negative number, it is recognized as 0, that is, starting from 0, which can be equivalent to str.substring(0)
    console.log(str.substr(-3))       //"ld!"
    
    console.log(str.slice(3,-4))      //"lo Wo"
    console.log(str.substring(3,-4))  //"Hel" 	 Since the second value passed in is negative, it is recognized as 0. Since the position of 0 is lower than 3, it can be equivalent to str.substring(0,3)
    console.log(str.substr(3,-4))     //"" 	 Since the end is a negative number, it is recognized as 0, that is, 0 characters are output, and the result is an empty character
    
  5. Use of method of type Number

    1. This type overrides the valueOf, toString and toLocaleString methods, where valueOf returns the original value of the object, and the latter two methods return the string of numeric values; The toString method can receive a parameter to represent the cardinality

      let num = 10
      console.log(num.toString())	  //"10"
      console.log(num.toString(2))  //"1010"
      console.log(num.toString(8))  //"12"
      console.log(num.toString(16)) //"a"
      
    2. The toFixed method returns a numeric string containing the specified number of decimal places, where the passed in parameter is the number of decimal places.

      let num = 10
      console.log(num.toFixed(2))	 //"10.00"
      

      toExponential returns the numeric string represented by scientific counting method. It can also receive a parameter representing the number of decimal places in the result.

      let num = 10
      console.log(num.toExponential(1))	//"1.0e+1"
      

      The toPrecision method returns the most appropriate form. The result depends on the situation. It may be in the form of fixed length or scientific counting. This method passes in a parameter that represents the total number of digits (excluding exponent) of the number in the result

      let num = 99
      console.log(num.toFixed(2))         //"99.00"
      console.log(num.toExponential(1))   //"9.9e+1"
      console.log(num.toPrecision(2))     //"99"
      
      console.log(num.toPrecision(1))     //"1e+2" needs to be represented by one digit, so it needs to be rounded
      console.log(num.toPrecision(3))     //"99.0" is represented by three digits
      

      The isInteger method identifies whether a value is saved as an integer

  6. A javaScript string consists of 16 bit symbols, each of which corresponds to one character.

    1. The charAt method returns the character at the given index position, specified by the integer parameter passed to the method.
    2. The charCodeAt method can view the character encoding of the specified symbol, return the symbol value of the specified index position, and the index is specified as an integer.
    3. fromCharCode can create characters in a string according to a given symbol, receive any number of values, and return a string that splices the characters corresponding to all values
  7. The 16 bit symbol can only represent 65536 characters, which is a Basic Multilingual plane BMP. Another 16 bits can be used to select a supplementary plane. This strategy of using two 16 bit symbols per character is a proxy pair.

    [page117](D:.Study\javascript\JavaScript advanced programming (4th edition Chinese HD) pdf)

  8. String position method

    1. indexOf finds the string from the beginning of the string and returns the position. Otherwise, it returns - 1
    2. lastIndexOf starts at the end of the string
    3. Both methods can specify a second parameter, which represents the starting position of the search. indexOf searches the string from the position of the parameter, ignoring the characters before the position; lastIndexOf searches from the position specified by the parameter to the beginning of the string;
    let str = "Lorem ipsum dolor sit amet, consectetur adipisicing elit"
    let pos = str.indexOf("e")
    let position = new Array()
    
    while(pos > -1){
      position.push(pos)
      pos = str.indexOf("e",pos+1)
    }
    
    console.log(position)
    //Using this method, you can call indexOf repeatedly and finally find all the target substrings
    
  9. String containing method

    1. Judge whether the string contains another string method startsWith, endsWith and includes. Searches for the incoming string from the string and returns a Boolean value indicating whether it is included.

    2. startsWith starts with index 0, endsWith starts with index (string.length - substring.length), and includes retrieves the entire string

      let meg = "foobarbaz"
      console.log(meg.startsWith("foo"))  //true
      console.log(meg.startsWith("bar"))  //false
      
      console.log(meg.endsWith("baz"))  //true
      console.log(meg.endsWith("bar"))  //false
      
      console.log(meg.includes("bar"))  //true
      console.log(meg.includes("qux"))  //false
      

      The startsWith and includes methods can receive the second parameter, indicating the starting position of the search, that is, from the specified position to the end of the string. The second parameter accepted by endsWith is the position that should be regarded as the end of the string, that is, the position from back to front;

  10. trim repeat and other methods

    1. trim creates a copy of the string, deletes all space characters before and after (that is, the space characters in the middle are not affected), and then returns the result
    2. repeat receives an integer parameter indicating the number of times the string is copied, and returns the result after splicing all copies
    3. padStart padEnd copies the string. If it is less than the specified length, fill the corresponding side with characters until the length condition is met. The first bit of the passed in parameter is the length, and the second is an optional fill string. The default space is not limited to one character. It will be truncated when it exceeds the length
  11. String iteration and Deconstruction

    A @ @ iterator method is exposed on the prototype of the string, indicating that each character of the string can be iterated

    let message = "abc"; 
    let stringIterator = message[Symbol.iterator](); 
    console.log(stringIterator.next()); // {value: "a", done: false} 
    console.log(stringIterator.next()); // {value: "b", done: false} 
    console.log(stringIterator.next()); // {value: "c", done: false} 
    console.log(stringIterator.next()); // {value: undefined, done: true}
    
    //In the for of loop, each character can be accessed sequentially through this iterator:
    for (const c of "abcde") { 
     console.log(c); 
    } 
    // a 
    // b 
    // c 
    // d 
    // e
    
    
    //With this iterator, the string can be deconstructed by the deconstruction operator. For example, you can more easily divide a string into character arrays:
    let message = "abcde"; 
    console.log([...message]); // ["a", "b", "c", "d", "e"]
    
  12. String case conversion

    toLowerCase,toLocaleLowerCase,toUpperCase,toLocaleUpperCase

  13. String pattern matching method

    match receives a parameter, which can be a regular expression string or a RegExp object. The returned array is the same as the array returned by the exec method of the RegExp object: the first element is a string matching the entire pattern, and the other elements are strings matching the capture group in the expression.

    let msg = "aatc, batr, sdat, atss"
    let pattern = /.at/
    
    let matches = msg.match(pattern)
    console.log(matches.index)
    console.log(matches[0])
    console.log(matches.lastIndex)
    console.log(matches)
    

    search receives the same as match. It returns the location index of the first match in the pattern. If it is found, it returns - 1. It always matches backwards from the beginning of the string

    let text = "cat, bat, sat, fat"; 
    let pos = text.search(/at/); 
    console.log(pos); // 1
    

    Replace receives parameter 1 as a RegExp object or a string, and parameter 2 as a string or a function. If first argument is a string, only first substring is replaced. To replace all substrings, the first parameter must be a regular expression with a global flag [the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-kq85qra3-1641293737957) (C: \ users \ czhho \ appdata \ roaming \ typora \ typora user images \ 1641199225928. PNG)]

    let msg = "cat, bat, sat, fat"
    result = msg.replace(/(.at)/g, "word($1)")
    console.log(result)
    //"word(cat), word(bat), word(sat), word(fat)"
    

    split splits the string into an array based on the passed in delimiter. The argument as a delimiter can be a string or a RegExp object. You can pass in the second parameter, array size, to ensure that the returned array does not exceed the specified size.

    let msg = "red,blue,green,yellow"
    let col1 = msg.split(",")
    let col2 = msg.split(",",2)
    let col3 = msg.split(/[^,a-d]+/)
    console.log(col1)	// ["red", "blue", "green", "yellow"]
    console.log(col2)	// ["red", "blue"]
    console.log(col3)	// ['','d,b ',', ',' '] there are two empty strings before and after the returned array because the separator specified in the regular expression appears at the beginning and end of the string
    

    localCompare compares two strings and returns one of the following three values

    1. In alphabetical order, strings should precede string parameters, i.e. return negative values(-1);
    2. If equal, return 0;
    3. Returns a positive value (1) if the string should follow the string parameter)
    
    let msg = "yellow"
    console.log(msg.localeCompare("block"))     //1
    console.log(msg.localeCompare("yellow"))    //0
    console.log(msg.localeCompare("zoo"))       //-1
    
    console.log(msg.localeCompare("yes"))       //-1 if the previous characters cannot be compared, continue the comparison later
    console.log(msg.localeCompare("yellow"))    //0 
    console.log(msg.localeCompare("year"))      //1
    

    The specific value returned may vary according to the specific implementation, and the implementation in different regions may be different, and it is case sensitive, with uppercase letters before lowercase letters

    function determineOrder(value, compareValue) {
      let res = value.localeCompare(compareValue)
      if(res < 0){
        console.log(`The string '${value}' comes before the string '${compareValue}'.`)
      }
      else if(res > 0){
        console.log(`The string '${value}' comes after the string '${compareValue}'.`)
      }
      else{
        console.log(`The string '${value}' is equal to the string '${compareValue}'.`)
      }
    }
    
    let val = "yellow"
    determineOrder(val,"brick")
    determineOrder(val,"yellow")
    determineOrder(val,"zoo")
    /**
     * The string 'yellow' comes after the string 'brick'.
     * The string 'yellow' is equal to the string 'yellow'.
     * The string 'yellow' comes before the string 'zoo'.
     */
    
  14. [the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG aochwjnf-16412937957) (C: \ users \ czhho \ appdata \ roaming \ typora user images \ 1641209004417. PNG)]

  15. Built in objects are any objects provided by the ES implementation, independent of the host environment, and existing at the beginning of the execution of the ES program, including Object, Array, and String

  16. Global targets properties and methods that do not belong to any object. In fact, there are no global variables or global functions. Variables and functions defined in the global scope will become properties of global objects.

  17. encodeURI,encodeURIComponent,decodeURI,decodeURIComponent

    The first two are used to encode the Uniform Resource Identifier URI for transmission to the browser. A valid URI cannot contain characters such as spaces.

    encodeURI is used to encode the whole URI and will not encode special characters that do not belong to URL components, such as colon, slash, question mark, pound sign, etc;

    encodeURIComponent encodes all nonstandard characters it finds

    The last two are the first two corresponding inverse operations. The four methods replace escape and unescape methods

    let uri =  "http://www.wrox.com/illegal value.js#start"
    
    //http://www.wrox.com/illegal%20value.js#start
    console.log(encodeURI(uri))
    //http%3A%2F%2Fwww.wrox.com%2Fillegal%20value.js%23start
    console.log(encodeURIComponent(uri))
    
    let uri1 =  "http%3A%2F%2Fwww.wrox.com%2Fillegal%20value.js%23start"
    
    //http%3A%2F%2Fwww.wrox.com%2Fillegal value.js%23start
    console.log(decodeURI(uri1))
    //http://www.wrox.com/illegal value.js#start
    console.log(decodeURIComponent(uri1))
    
  18. Eval receives a parameter, that is, an ES string to be executed, which will be interpreted as the actual es statement and inserted into the current location. The code executed in Eval belongs to the context of the call, and the executed code has the same scope chain as the context. That means that variables defined in the containing context can be referenced inside the eval call. Any variables and functions defined through Eval are not promoted.

    let msg = "hello world!"
    eval("console.log(msg)")    //Output msg
    
    eval("function sayHi(){console.log('hi');}")
    sayHi()     //This function can be called externally
    
  19. The window object ECMA-262 does not specify the way to directly access the Global object, so the browser implements the window object as a proxy for the Global object. All variables and functions declared in the Global scope become window properties.

    var color = "red"
    
    function sayColor() {
      console.log(window.color)
    }
    
    window.sayColor()   //"red"
    
  20. When a function is executed without specifying the value of this explicitly (through a method that becomes an object, or through call()/apply()), the value of this is equal to the Global object. Calling a function that simply returns this is a common way to get a Global object in any execution context.

  21. The ES provides math objects as a place to save mathematical formulas, information and calculations, and provides some properties and methods to assist in calculations. The calculation provided on the Math object is much faster than that directly implemented on JS, because the calculation on the Math object uses more efficient implementation and processor commands in the JavaScript engine. However, the accuracy varies in many ways.

    [the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-nxg5jo6h-16412937958) (C: \ users \ czhho \ appdata \ roaming \ typora user images \ 1641222575622. PNG)]

    min max is used to determine the maximum and minimum values, and can receive any number of parameters

    Math.ceil is always rounded up to the nearest integer

    Math.floor is always rounded down to the nearest integer

    Math.round performs rounding

    Math. Forward returns the closest single precision (32-bit) floating-point value representation of a value

  22. random method

    Math. The random () method returns a random number in the range of 0 ~ 1, including 0 but not 1. Obtain a number formula randomly from a set of integers:

    number = Math.floor(Math.random() * total_number_of_choices + first_possible_value)

    Including total_number_of_choices refers to the total number of this group of integers, first_possible_value is the smallest possible number of this set of integers

    function selectFrom(lowerNum, upperNum) {
      let choices = upperNum - lowerNum + 1
      let res = Math.floor(Math.random() * choices + lowerNum)
      return res
    }
    
    let num = selectFrom(2, 10)
    console.log(num)
    
    // Used to randomly select an element from an array
    let colors = ["red", "green", "blue", "yellow", "black", "purple", "brown"]
    let color = colors[selectFrom(0, colors.length - 1)]
    console.log(color)
    
    // Random numbers need to be generated for encryption. It is recommended to use window crypto. getRandomValues()
    

    [the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-zob4upky-16412937958) (C: \ users \ czhho \ appdata \ roaming \ typora user images \ 164122364136. PNG)]

erNum, upperNum) {
let choices = upperNum - lowerNum + 1
let res = Math.floor(Math.random() * choices + lowerNum)
return res
}

let num = selectFrom(2, 10)
console.log(num)

// Used to randomly select an element from an array
let colors = ["red", "green", "blue", "yellow", "black", "purple", "brown"]
let color = colors[selectFrom(0, colors.length - 1)]
console.log(color)

// Random numbers need to be generated for encryption. It is recommended to use window crypto. getRandomValues()
```

[External chain picture transfer...(img-ZOB4UpKY-1641293737958)]

Topics: Javascript