Reference Types of JS Red Book Notes

Chapter 5 Reference Types

The value (object) of a reference type is an instance of the reference type. And similar.

ECMAScript provides many native reference types (such as Object)

5.1 Object type

Objects are called reference type values ​​in JS. Object is a basic type, and all other types inherit basic behavior from object.

5.1.1 There are two ways to create an Object instance

  • var person = new Object() //Use the new operator followed by the Object constructor
  • var person = {} // Use object literal notation, the property name can be added or not quoted.

In a subject can be used typeof obj.prop == 'string' | 'number'...to determine this property there

5.1.2 Access object properties

  • Point notation (more recommended): obj.name
  • Square bracket method: obj["name"]
    • The main advantage of square brackets is that you can use variables to access properties, for example: var a = "name", obj[a] == obj["name"]. When the attribute name contains characters that can cause grammatical errors (for example, there are spaces between the characters), it is better to use square brackets.

5.2 Array type

5.2.1 Two ways to create an Array type

  • var arr = new Array(nums|...arr:Sring) //If you know the number of items in advance, you can add the nums parameter setting. Or you can set the items in it in advance. You can also omit new:var arr = Array()
  • var arr = []

5.2.2 The length property of the array

arr.length It can be read or written. When the length is smaller than the original length, the following items will be deleted. When the length is greater than the original length, the items will be added later (undefined)

You can also directly set the value after the length is greater than the length. arr[arr.length+n] = number, the length of the array will become arr.length+n+1

5.2.3 Detection array

Array.isArray(arr)

5.2.4 Array method

Conversion method

  • arr.toSring(): returns a comma-separated string

  • arr.valueof(): returns an array

  • arr.toLocaleString(): returns a comma-separated string

  • arr.join(''): returns a string separated by specified symbols

Stack method

  • arr.push('','' …) returns the length of the modified array
  • arr.pop() removes the last item and returns the removed item

Queue method

  • arr.shift() removes the first item and returns the removed item
  • arr.unshift adds an item to the front end and returns the length of the modified array

Reorder

  • arr.sort(), The sort() method will call toString() of each array item, and then compare, that is, the ascaII code is compared.

Therefore sort() can accept a comparison function as a parameter. The order will be reversed when the comparison function returns 1.

  • arr.reverse()Functions can be reversed directly, even if there is no order.

Method of operation

  • var narr = arr.concat('',[]). This method first creates a copy of the current array, and then adds the received parameters to the end.
  • var narr = arr.slice(start, [end]) returns the array formed from index start to the previous one at end
  • var narr = arr.splice(start,len,…[]) returns an array of length len from the index start, the original array arr will be cut

Location method

  • arr.indexOf(item,[index]), starting from the index inedx, looking backward, looking for item, and returning the index value
  • arr.lastIndexOf(item,[index]) From the index index, look forward, find item, and return the index value

Iterative method

  • every() If each item returns true, it returns true
  • filter() returns an array of true items
  • forEach() runs a function for each item, no return value
  • map() returns an array of the results of each item call function
  • some() If one item returns true, it returns true

Shrinking method

The difference between the two is only starting from the left and starting from the right

  • reduce(func(prev,cur,index,array),initvalue) iterates all items in the array and returns the final iteration value.
  • reduceRight()

5.3 Date type

The Date type uses the number of milliseconds that have passed since UTC January 1, 1970 to save the date.

5.3.1 How to create Date

var now = new Date(), Which can accept parameters (number of milliseconds) and return a specific time.

5.3.2 Date method

  • Date.parse() receives a string parameter representing the date and returns the number of milliseconds of the corresponding date
  • Date.UTC() It has a fixed parameter format to represent the date, and returns the number of milliseconds of the response date
  • Date.now () returns the number of milliseconds call this method (the +new Date()same as)
  • d.toLocaleString() will return the date and time in the format corresponding to the region set by the browser
  • d.toSring() will return the date and time with missing information
  • d.valueOf() will return the number of milliseconds (valueOf is automatically called when the date is compared)
  • getFullYear() Get the 4-digit year
  • getMonth() Get the month (0 is January, 11 is December)
  • getDate() returns the number
  • getDay() returns the day of the week (0 is Sunday, 6 is Saturday)
  • getHours()
  • getMinutes()
  • getSeconds()

5.4 RegExp type

5.4.1 Matching Mode

  • g Global mode, that is, it does not stop when the first match is found
  • i not case sensitive
  • m Multi-line mode, that is, when it reaches the end of a line, it will continue to find the next line

5.4.2 The difference between literal and constructor creation

var re = null
for(var i = 0; i < 10; i++){
    
    
    re = /cat/g                    //注意使用字面量形式时不用加引号
    re.test('catastrophe')
}
for(var i = 0; i < 10; i++){
    
    
	re = new RegExp('cat',g)
    re.test('catastrophe')
}

Regular expression literals always share the same RegExp instance, and new instances created using the constructor are independent.

So the first loop starts from the character with index 3 in the second call, so it can't be found.

.

.

.

To be continued

5.5 Function type

Since functions are objects, so the function name is actually a pointer to the function object pointer

5.5.1 Ways to define functions

  • function sum () {}: function declaration, the parser will read the function declaration first and make it available before executing any code
  • var sum = function() {}: function expression, only when the parser executes it will it be interpreted and executed
  • var sum = new Function("","","") Use the Function constructor. The previous parameter is the parameter of the function, and the last parameter is the function body (not recommended, it will be parsed twice)

Without function overloading, functions defined later will override functions defined earlier.

To access the pointer of the function without executing the function, you must remove the pair of parentheses after the function name (when passing the function as a parameter)

5.5.2 Function internal properties

Inside the function, there are two special objects: arguments and this

  • Arguments is an array-like object that contains all the parameters passed into the function. It has an attribute called callee, which is a pointer to the function that owns the arguments
  • This refers to the environment object in which the function data is executed. The point of this cannot be determined when the function is created. It can only be determined when the function is called. Whoever calls will point to whom
    • If there is this in a function, but it is not called by the upper-level object, then this points to window. What needs to be explained here is that in the strict version of js this points to not window, but we will not discuss the strict version here. If you want to know about the problem, you can find it on the Internet.
    • If there is this in a function and this function is called by an object at the upper level, then this points to the object at the upper level.
    • If there is this in a function, this function contains multiple objects, even though this function is called by the outermost object, this only points to the object at the upper level.
  • caller This attribute holds the reference of the function that called the current function. If the current function is called in the global scope, its value is null
  • length It returns the number of named parameters that the function expects to accept
  • apply() and call() and bind() are all calling functions in a specific scope, which is actually equivalent to setting the value of this object in the function body

5.6 Basic packaging types

In fact, every time a basic type value is read, a corresponding basic packaging type object is created in the background.

E.g:var s1 = "some text" var s2 = s1.substring(2)

Logically, basic types are not objects and should not have methods, but methods can be called. In fact, in the read mode, the background will automatically complete the following processing:

  • Create an instance of String type new String("some text")
  • Call the specified method on the instance
  • Destroy this instance

Instances of reference types created using the new operator are kept in memory until the execution flow leaves the current scope. The automatically created objects of the basic packaging type only exist at the moment of execution of a line of code, and then are destroyed immediately. This means that we can no longer add properties and methods to basic types at runtime.

5.7 Boolean type

All objects in the Boolean expression will be converted to true.

var falseobj = new Boolean(false)
var result = faluseobj&&true
alert(result)   //true

5.8 Number type

  • num.toString(x) The parameter x is expressed as an x ​​base and expressed as a string
  • num.toFixed(x) The parameter x means that the returned value is expressed as a string according to the specified x decimal place
  • num.toExponential(x) returns a string expressed in exponential notation, x specifies the number of decimal places
  • num.toPrecision(x) x represents the number of digits of all digits of the value (excluding the exponent part), and then returns the above appropriate format

5.9 String type

  • str.charAt(index) returns the character at a given position
  • str.charCodeAt(index) returns the Ascii code of the character at a given position
  • str1.concat(str2,str3…)

The following three have no effect on the original string, and will return a new cut substring

  • str.slice(start,[end]) //Does not include end
  • str.substr(start,[length])
  • str.substring(start,[end])

Location method

  • str.indexOf(substring,[start])
  • str.lastIndexOf(子串,[start])

.

.

.

There are many ways

5.10 Single built-in objects

Built-in objects refer to "objects that are provided by the ECMAScript implementation and do not depend on the host environment. These objects exist before the execution of the ECMAScript program, such as Object Array String", as well as the two single built-in objects Global (global) and Math ( Before all the code is executed, these two objects exist in the scope).

  • Global : The encodeURI() and encodeURIComponent() methods of this object can encode the URI (Universal Resource Identifier) ​​for sending to the browser.

    • Any variables or functions created in the eval() method will not be promoted
  • Math

    • Math.max()
    • Math.min ()
    • Math.ceil() | floor() | round()
    • Math.random()

Guess you like

Origin blog.csdn.net/Pinoochio/article/details/113688599