Summary of JavaScript Advanced Programming Chapter 5 Reference Types

Keywords: Javascript Attribute encoding

A reference type is a data structure that represents an abstract set. The instantiation is then the object.


Reference Type (or Understand as Class) -------------- (Instance) ----------------> Object


In javascript, reference types are instances of Object types.


- There are two ways to create an object (Object instance).

1) Use a new Object type approach, such as:

	var obj = new Object()

2) Object literals

	var obj = {
		name:'John',
		age:'25'
	}
	var obj2 = {}

- Two methods of invoking:

	console.log(obj.name)//John
	console.log(obj['name'])


- Array type

Array type is used to create arrays, each item of the array can store any type of data, and the length of the array can be dynamically adjusted.

Arrays are created by:

1) Constructed by Array Type

	var colors = new Array()
	var colors = new Array(20)//Create an array of length 20
	var colors = new Array('red','blue','green')//Create arrays and assign values
	var colors = Array(3)//new can also be omitted
	var colors = Array('red','blue','green')//new can also be omitted

2) Array literal representation

	var colors = ['red','blue','green']
	var names = []

Detection array: Array.isArray(value)


Conversion methods: toLocaleString(),toString(),valueOf(),join()
The valueOf() method still returns an array.
When printing an output array, the toString() method is implicitly called. For example, console.log() and alert()
The join() method sets the separator.

	var colors = ['red','blue','green']
	console.log(colors.join('||')) //red||blue||green


Stack methods: push(),pop()

Sorting method:
reverse() // Inversion of the original array item, directly changing the original array
sort() // Sort by string size, directly changing the original array
For sort(), it can set a function to specify the comparison method between each two numbers. demo is as follows:

	var values = [2,60,30,5,66]
	values.sort(function(value1,value2){
		return value1 - value2
	})
	console.log(values)//2,5,30,60,66

Method of operation:
concat() // Stitching arrays, returning stitched arrays

	var arr = [1,2,3,4]
	var arr2 = arr.concat(5,[6,7])
	console.log(arr2)
slice()// intercepts some elements of the array and returns without changing the original array

	var arr = ['I','am','a','student','in','UESTC']
	var arr1 = arr.slice(1)
	var arr2 = arr.slice(1,3)
	console.log(arr1)//am,a,student,in,UESTC
	console.log(arr2)//am,a
splice() // Deleting, inserting and replacing arrays will affect the original array and return deleted items.
	var arr = ['I','am','a','student','in','UESTC']
	var otherArr = arr.splice(2,1)//Delete from item 3 and delete one element
	console.log(arr)//'I','am','student','in','UESTC'
	console.log(otherArr)//'a'
	
	otherArr = arr.splice(2,0,'a')//Insert from item 3
	console.log(arr)//'I','am','a','student','in','UESTC'
	console.log(otherArr)//''
	
	otherArr = arr.splice(2,2,'not','a','gay')//Delete items 3 and 4 and insert
	console.log(arr)//["I", "am", "not", "a", "gay", "in", "UESTC"]
	console.log(otherArr)//["a", "student"]

Location method:
indexOf(),lastIndexOf()
Find its index position in the array by value

Iterative methods (methods that run on each item of an array):
every() // Each item of the array returns true after running the function, then true
filter() // After each run function, return the true items to form an array and return
forEach() // Each run function has no return value
map() // For each running function of an array, the result returned by the function forms a new array and returns it.
some() // Each run function returns true if one returns true

	var numArr = [1,2,3,4,5,6,5,4,3,2,1]
	
	var everyResult = numArr.every(function(item,index,array){
		//Item, each item; index, index number; array, array itself
		return (item>2)
	})
	console.log(everyResult)//false
	
	var someResult = numArr.some(function(item,index,array){
		return (item>2)
	})
	console.log(someResult)//true
	
	var filterResult = numArr.filter(function(item,index,array){
		return (item>2)
	})
	console.log(filterResult)//[3,4,5,6,5,4,3]
	
	var mapResult = numArr.map(function(item,index,array){
		return item*2
	})
	console.log(mapResult)//[2,4,6,8,10,12,10,8,6,4,2]
	
	numArr.forEach(function(item,index,array){
		return item+1
	})
	console.log(numArr)//[1,2,3,4,5,6,5,4,3,2,1]

Merging method:
reduce() // Iterate all items of the array, return a final value, and iterate from the first item
rightReduce() // Iterate all items of the array, return a final value, and iterate from the last item
	var values = [1,2,3,4,5]
	var sum = values.reduce(function(prev,cur,index,array){
		//prev, the former item; cur, the current item; index, the current item index; array array array object
		//In the first iteration, prev == 1, cur === 2
		//The second time, prev = 3, cur = 4
		return prev + cur
	})
	console.log(sum)


- Date type

	var now = new Date()	
	var now = Date.now()	//Millisecond representation	
	var now = +new Date()	//Millisecond representation
When using, consult relevant documents


- Function type
Each function is an instance of the Function type, and the function name is a pointer to the function.

Function declaration:

	function sum(num1,num2){return num1+num2}	//Parser pre-parsing
Functional expressions:

	var sum = function(num1,num2){return num1+num2}	//Parsers parse in sequence
A pointer to the sum access function, and sum() a direct call to the function

Examples of passing functions as values:

	var data = [{name:'John',age:28},{name:'Jam',age:20}]
	function createCompareFunction(propertyName){
		return function(obj1,obj2){
			var value1 = obj1[propertyName]
			var value2 = obj2[propertyName]
			return value1 - value2
		}
	}
	data.sort(createCompareFunction('age'))

Function internal properties:

The parameter set of the arguments function, which is an array-like object that can be manipulated by an array method
callee() calls arguments.callee(), pointing to the function itself to which arguments belong, which is useful when calling back
this points to the object corresponding to the current execution environment
caller finds the function that references the current function, using the following:

	function outerFn(){
		innerFn()
	}
	function innerFn(){
		console.log(innerFn.caller)//outerFn
	}
	outerFn()

The attributes and methods of functions:
Attribute: fnName.length represents the number of named parameters the function wants to accept
The prototype of fnName.prototype pointing function
Method: apply() calls the function directly when using this method, passing in an array of parameters
call() calls the function directly when using this method, and the parameters passed in are listed.
Instead of calling a function directly, bind() returns a function.
The first parameter of these three methods is passed in an object (or this keyword) to change the execution environment (scope).
The latter parameter is passed in as the parameter of the called function

call() example:

			var obj = {
				saying:'Hi'
			}
			function sayHi(name){
				console.log(name+'say:'+this.saying)
			}
			sayHi.call(obj,'John')//John is passed in as a parameter of the function sayHi().

apply() example:

			function sum(num1,num2){
				return num1+num2
			}
			function callSum1(num1,num2){
				//return sum.apply(this,[num1,num2])
				return sum.apply(this,arguments)//Even if this is not needed in the sum() function, an object must be passed in here.
			}
			callSum1(10,20)

The bind() example:

			var obj = {
				saying:'Hi'
			}
			function sayHi(name){
				console.log(name+'say:'+this.saying)
			}
			var otherFn = sayHi.bind(obj,'John')//John is passed in as a parameter of the function sayHi().
			otherFn()


- Basic Packaging Types

JavaScript provides three special reference types: Boolean,Number,String, which correspond to their respective basic types
When a basic value is read, the background creates a corresponding basic wrapper type.
When calling a method of the wrapper type corresponding to the base type, it looks like this

	var s1 = 'some text'
	var s2 = s1.substring(2)
Background will produce the following process:
(1) Create an instance of String type
(2) Call the specified method on the instance
(3) Destroy this example

Boolean objects should not be used as much as possible

String type:
Each instance of String type has a length attribute, which is used to get the number of characters in a string.

The operation method of a single character:
There are charAt() and charCodeAt() ways to access individual characters in a string based on their location.
charAt() Finds a single character in the corresponding position
charCodeAt() finds a single character at the corresponding position and converts it into character encoding
In addition, strings can access individual characters like arrays, such as

			var stringValue = 'hello world'
			console.log(stringValue[1])

String operation method:
concat() string splicing

			var stringValue = 'hello'
			var result = stringValue.concat(' ','world','!!!')
			console.log(result)//hello world!!!
slice(),substr(),substring()
The purpose of these three methods is the same. They are all to intercept part of the string and return it without changing the original string, and try to use slice().

String position method:
indexOf('substring',start),lastIndexOf() 
The first parameter passes in a substring to find its corresponding position in the original string; the second parameter passes in the starting position of the search.
Stop at the first place where you find'substring'and stop searching

The trim() method returns a copy after removing the spaces at both ends of the string.

String pattern matching method match(), the original book p126, read and summarize.

The localeCompare() method compares two strings and returns 1, -1, 0
string1.localeCompare(string2), which is not very important, look at the api documentation when you use it.

fromCharCode() method, encoding characters - > strings
console.log(String.fromCharCode(104,101,108,108,111)) //'hello'


- Single-body built-in object
Meaning of built-in objects: Has been instantiated without the need for programmers to explicitly instantiate, such as Object,Array,String
In addition, there are two single built-in objects, Global,Math


eval() passes in a string as an execution object, which is compiled and executed by this method


Math object
Attributes Math.E, Math.Ln10, Math.Ln2, Math.LOG2E, Math.LOG10E, Math.PI, Math.SQRT1_2, Math.SQRT2


max(),min() method:

			var max = Math.max(3,54,32,16)
			console.log(max) // 54
			
			var arr = [1,2,3,4,5,6,7,8,9,10]
			var max = Math.max.apply(Math,arr)//Math must be passed in to specify the execution environment, which is a fixed format
Rounding method:

Math.ceil() rounded up
Math.floor() integrates downward
Math.round() rounded


random() method:
Math.random() creates a number x whose range of values is 0<=x<1


Randomly create one from lowerValue to upperValue

			function selectFrom(lowerValue,upperValue){
				var choices = upperValue - lowerValue + 1
				return Math.floor(Math.random()*choices + lowerValue)
			}
Other methods
Math.abs(n), Math.exp(n), Math.log(num), Math.pow(num,power), Math.sqrt(num), Math.acos(x)
Math.asin(x), Math.atan(x), Math.atan2(y,x), Math.cos(x), Math.sin(x), Math.tan(x)

Posted by kjtocool on Sat, 29 Jun 2019 14:04:53 -0700