JavaScript basics 09-day11 [prototype object, toString(), garbage collection, array, array literal, array method]

Study address:

  1. Grain Academy-Shang Silicon Valley
  2. Bilibili website——Silicon Valley's latest version of JavaScript basic full set of tutorials (140 episodes of practical teaching, JS from entry to master)

Summary of JavaScript basics and advanced study notes [Silicon Valley latest version of the full set of JavaScript basic tutorials (140 episodes of practical teaching, JS from entry to master)]

table of Contents

P65 65. Shang Silicon Valley _JS Foundation _. Constructor modification 10:29

P66 66. Still Silicon Valley_JS Foundation_Prototype Object 20:43

Prototype

Add attributes to the prototype

Add method to prototype

P67 67. Still Silicon Valley_JS Foundation_Prototype Object 11:16

Use "in" to check whether the object contains an attribute

P68 68. Shang Silicon Valley_JS Foundation_toString() 11:33

Object.toString()

Modify the toString of the prototype

P69 69. Still Silicon Valley_JS Foundation_Garbage Collection 09:19

Garbage collection (GC) garbage collection

P70 70. Shang Silicon Valley_JS Basics_Array Introduction 24:46

Classification of objects

Array

Add elements to the array

Find elements in the array

Get array length

Modify array length

Add an element to the last position of the array

P71 71. Shang Silicon Valley_JS Basics_Array Literal 14:19

Use "literal" to create an array

The elements in the array can be of any data type!

P72 72. Four methods of _JS basic_array in Silicon Valley 13:45

Array object properties

Array object methods

1、push()

2、pop()

3、unshift()

4、shift()

P73 73. Shang Silicon Valley_JS Basics_Array Traversal 13:45

Small exercise

P74 74. Shang Silicon Valley_JS Basics_Array Exercise 04:52

P75 75. Still Silicon Valley_JS Foundation_forEach 13:15

P76 76. Still Silicon Valley_JS Foundation_slice and splice 18:25

slice()

splice()

P77 77. Shang Silicon Valley_JS Basics_Array Deduplication Exercise 13:34


P65 65. Shang Silicon Valley _JS Foundation _. Constructor modification 10:29

Create a Person constructor. In the Person constructor, a sayName method is added for each object.

At present, our method is created inside the constructor, that is, a new sayName method is created every time the constructor is executed, and the sayName of all instances is unique.

This leads to the creation of a new method when the constructor is executed once, 10,000 new methods are created when executed 10,000 times, and 10,000 methods are exactly the same.

This is completely unnecessary, it is possible to make all objects share the same method.

P66 66. Still Silicon Valley_JS Foundation_Prototype Object 20:43

If it is written in the Person object, every time a new Person is created, the sayName method object will be created, wasting memory. But if it is placed outside, sayName() belongs to the Window object, and the sayName in all objects is the sayName in the called external Window object. Benefits: easy to maintain, if two constructors have the same function function, they can be written separately, without having to change every part of the function every time.

Defining functions in the global scope pollutes the namespace of the global scope, and it is not safe to define them in the global scope.

Prototype

For every function we create, the parser adds an attribute prototype to the function. This property corresponds to an object, which is what we call the prototype object.

If the function is called as an ordinary function to call the prototype has no effect, when the function is called in the form of a constructor, there will be an implicit attribute in the object it creates, pointing to the prototype object of the constructor, we can use __proto__ to Access the property.

The prototype object is equivalent to a public area. All instances of the same class can access this prototype object. We can set the common content of the object to the prototype object.

Add attributes to the prototype

When we access a property or method of an object, it will first look for it in the object itself, if there is one, use it directly, if not, look for it in the prototype object, and use it directly if it finds it.

Add method to prototype

When we create a constructor in the future, we can uniformly add the properties and methods common to these objects to the prototype object of the constructor .

In this way, without adding common properties and methods to each object separately , and without affecting the global scope, each object can have these properties and methods.

P67 67. Still Silicon Valley_JS Foundation_Prototype Object 11:16

Use "in" to check whether the object contains an attribute

The prototype object is also an object, so it also has a prototype.
   When we use a property or method of an object, we will find it in
      itself. If there is in itself, we will use it directly.
      If there is not , we will find in the prototype object . If there are in the prototype object, we will use it.
      If there is not , we will go to the prototype. Search in the prototype until the prototype of the
      Object object is found. The prototype of the Object object has no prototype. If it is still not found in the Object prototype, undefined is returned.

P68 68. Shang Silicon Valley_JS Foundation_toString() 11:33

Object.toString()

When we print an object directly on the page, the event is the return value of the toString() method of the output object.

Modify the toString of the prototype

When we print an object directly on the page, it is actually the return value of the toString() method of the output object.

If we want to not output "[object Object]" when outputting an object, we can add a toString() method to the object.

P69 69. Still Silicon Valley_JS Foundation_Garbage Collection 09:19

Garbage collection (GC) garbage collection

Garbage Collection (GC): Just like garbage will be generated when people live for a long time, garbage will also be generated during program operation.

When these garbage accumulates too much, it will cause the program to run too slowly, so we need a garbage collection mechanism to deal with the garbage generated during the running of the program.

When an object does not have any variables or attributes to refer to it, we will never be able to manipulate the object at this time, this kind of object is a rubbish at this time, this kind of object will take up a lot of memory space, causing the program to run slowly , So this garbage must be cleaned up.

There is an automatic garbage collection mechanism in JS, which will automatically destroy these garbage objects from memory. We do not need and cannot perform garbage collection operations. All we need to do is to set null for objects that are no longer used.

P70 70. Shang Silicon Valley_JS Basics_Array Introduction 24:46

Classification of objects

There are three types of objects:

  1. Built-in objects
  2. Host object
  3. Custom object

Array

Array

  1. An array is also an object.
  2. Its function is similar to our ordinary object , and it is also used to store some values.
  3. The difference is that ordinary objects use strings as attribute names, while arrays use numbers as index operation elements.
  4. Index: An integer starting from 0 is the index.
  5. The storage performance of arrays is better than that of ordinary objects. In development, we often use arrays to store some data.

Add elements to the array

Find elements in the array

Get array length

Get the length of the array, you can use the length property to get the length of the array (the number of elements).
Syntax: array.length

  • For continuous arrays, use length to get the length (number of elements) of the array.
  • For non-contiguous arrays, using length will get the largest index of the array +1. Try not to create non-contiguous arrays.

Modify array length

Modify length: If the modified length is greater than the original length, the extra part will be emptied. If the modified length is less than the original length, the extra element will be deleted.

Add an element to the last position of the array

Add an element to the last position of the array. Syntax: array [array.length] = value;

P71 71. Shang Silicon Valley_JS Basics_Array Literal 14:19

Use "literal" to create an array

Same as var arr = new Array(); to create an array, but [] is simpler and more convenient.

The elements in the array can be of any data type!

P72 72. Four methods of _JS basic_array in Silicon Valley 13:45

Array object properties

Array object methods

1、push()

push()

  • This method can add one or more elements to the end of the array and return the new length of the array.
  • You can pass the elements you want to add as parameters of the method, so these elements will be automatically added to the end of the array.
  • This method returns the new length of the array as the return value.

2、pop()

pop() : This method can delete the last element of the array and return the deleted element as the return value.

3、unshift()

unshift()

  • Add one or more elements to the beginning of the array and return the new array length.
  • After inserting an element to the front, the indexes of other elements will be adjusted in turn.

4、shift()

shift() : You can delete the first element of the array and return the deleted element as the return value.

P73 73. Shang Silicon Valley_JS Basics_Array Traversal 13:45

The so-called traversal of the array is to take out all the elements in the array.

Small exercise

P74 74. Shang Silicon Valley_JS Basics_Array Exercise 04:52

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript">
			function Person(name, age, gender) {
				this.name = name;
				this.age = age;
			}

			// 修改Person原型的toString
			Person.prototype.toString = function() {
				return "Person[name=" + this.name + ",age=" + this.age + "]";
			};

			//创建一个Person对象
			var per = new Person("孙悟空", 18);
			var per2 = new Person("猪八戒", 28);
			var per3 = new Person("红孩儿", 8);
			var per4 = new Person("蜘蛛精", 16);
			var per5 = new Person("二郎神", 38);

			// 将这些person对象放入到一个数组中
			var perArr = [per, per2, per3, per4, per5];
			console.log(perArr);

			/*
			 * 创建一个函数,可以将perArr中的满18岁的Person提取出来,
			 * 	然后封装到一个新的数组中并返回
			 * arr:形参,要提取信息的数组
			 */
			function getAdult(arr) {
				//创建一个新的数组
				var newArr = [];
				//遍历arr,获取arr中Person对象
				for (var i = 0; i < arr.length; i++) {
					var p = arr[i];
					//判断Person对象的age是否大于等于18
					if (p.age >= 18) {
						//如果大于等于18,则将这个对象添加到newArr中
						//将对象放入到新数组中
						newArr.push(p);
					}
				}
				//将新的数组返回
				return newArr;
			}

			var result = getAdult(perArr);
			console.log(result);
		</script>
	</head>
	<body>
	</body>
</html>

P75 75. Still Silicon Valley_JS Foundation_forEach 13:15

Generally we use the for loop to traverse the array. JS also provides us with a method to traverse the array: forEach().

This method only supports IE8 and above browsers, and IE8 and below browsers do not support this method, so if you need to be compatible with IE8, do not use forEach, or use a for loop to traverse.

The forEach() method requires a function as a parameter:

  • Functions like this, created by us but not called by us, are called callback functions .
  • If there are several elements in the array, the function will be executed several times. Each time it is executed, the browser will pass the traversed elements in the form of actual parameters. We can define formal parameters to read these contents.
  • The browser will pass three parameters in the callback function: [The first parameter is the element currently being traversed; the second parameter is the index of the element currently being traversed; the third parameter is the array being traversed.

P76 76. Still Silicon Valley_JS Foundation_slice and splice 18:25

slice()

slice()
     -can be used to extract the specified element from the array
     -this method does not change the element array, but encapsulates the intercepted elements into a new array and returns
     -Parameters:
         1. The index of the position where the interception starts, including the start index
         2. The index of the position where the interception ends, excluding the end index
             -the second parameter can be omitted without writing, at this time all elements from the start index will be intercepted
         -the index can be passed a negative value, if a negative value is passed, then Calculate from back to front
             -1 first to
             last -2 second to last

splice()

splice()
    -can be used to delete specified elements in an array.
    -Using splice() will affect the original array, delete the specified element from the original array, and return the deleted element as the return value.
    -Parameter: the
        first one, the
        second one indicates the index of the starting position ,
        and the third one and later the number of deletions .
            You can pass some new elements, these elements will be automatically inserted before the start position index

P77 77. Shang Silicon Valley_JS Basics_Array Deduplication Exercise 13:34

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript">
			//创建一个数组
			var arr = [1, 2, 3, 2, 2, 1, 3, 4, 2, 5];

			//去除数组中重复的数字
			//获取数组中的每一个元素
			for (var i = 0; i < arr.length; i++) {
				//console.log(arr[i]);
				/*获取当前元素后的所有元素*/
				for (var j = i + 1; j < arr.length; j++) {
					//console.log("---->"+arr[j]);
					//判断两个元素的值是否相等
					if (arr[i] == arr[j]) {
						//如果相等则证明出现了重复的元素,则删除j对应的元素
						arr.splice(j, 1);
						//当删除了当前j所在的元素以后,后边的元素会自动补位
						//此时将不会在比较这个元素吧,我需要在比较一次j所在位置的元素
						//使j自减
						j--;
					}
				}
			}
			console.log(arr);
		</script>
	</head>
	<body>
	</body>
</html>

Come on, go for it~

Guess you like

Origin blog.csdn.net/weixin_44949135/article/details/112707218