**— theme: channing-cyan
1. The target
- Develop the software development thinking of senior programmer
- Master the advanced writing of JS language
- Learn some unusual syntax
Based on the review
- variable
- Function of variables, syntax, naming rules
- Var: You can define variables, but the variable name is promoted. There is no concept of scope
- Let: There is no variable name promotion, it is defined before it is used, there is the concept of scope
- Const: Defines a constant (a variable that cannot be changed once it is assigned: members of a module are generally const thereafter)
- The data type
- Basic data types
- Also called value types
- Number String, Boolean, undefined, null
- Complex data types
- Also known as a reference type, it is essentially an address space
- Functions, arrays, objects
- Null of the reference type, usually set to NUL
- Basic data types
- Type conversion
- Convert to string
- toString()
- “+” “
- Convert to numbers
- ParseInt (): converts until a non-number is encountered, returning NaN if the first one is a non-number
- Number(): Returns NaN whenever there is a non-numeric string
- 0
- Converts to a Boolean value
- False in js: 0, “, “”, null, and undefined, NaN
- Boolean(variable to be converted)
- Convert to string
- The operator
- Arithmetic operator :+ – * / %
- The assignment operator :=
- Comparison operators:
- > < >= <= =! = = = =
- ==: Values must be equal, which converts strings to numeric values
- === : Values and types must also be equal
- Logical operators:! && | |
- The increment and decrement operator: ++ —
- Write first: Execute first, then use
- Write after: Use before you execute
- Precedence of operator :()
- Flow control statement
- Sequential structure
- Branch structure :if-else
- ForEach (function(value,index){})
- An array of
- There are two ways to create arrays
- Let arr = [] — syntax sugar
- let arr = new Array(…)
- Subscript and length
- There is only one attribute: Length
- Value and storage
- Through the index
- If you find that the data type of the operation is array, look for the index
- api
- Add: Push unshift
- Delete: splice (index, length)
- Alter: arr[I] =”
- Query: arr[I]
- There are two ways to create arrays
- function
- Declaration and invocation
- Parameters and arguments
- The number of corresponding
- Order the corresponding
- Type the corresponding
- The return value
- If the method does not return a value, undefined is returned by default
- Returns a value by return
- Only one return from a function can be executed
- A return can only return a variable, but an object is more commonly used
- object
- How to create objects :{}
- Properties and methods: Characteristics and behaviors
- Store values and values
- Values are stored and retrieved using keys
- Obj [key]: If key is a variable, the operation can only be performed in [] mode
- obj.key
- Assignment:
- If the key already exists, it is modified
- If the key does not exist, add – dynamic characteristics
- Values are stored and retrieved using keys
- Object traversal
- for.. in >> for(let key in obj) {}
- Built-in objects
- Math
- The static type
- The Math constructor calls its members directly
- Common: Floor Ceil random ABS
- Array
- Date
- New Date(): Gets the current Date
- Date.now(): Gets the value of milliseconds between the current Date and the default Date
- String
- Math
typeof
The keyword
The typeof operator returns a string that returns the typeof the operand
-
Typeof primitive types return string values
- String string
- Bool “Boolean
- Value “number”
-
A Typeof object returns object
-
The Typeof function returns function
-
Typeof NULL Returns an object
-
Typeof undefined: returns undefined
-
Typeof Array: Returns Object
Logic interrupt
&& : Evaluates from left to right. If you find that the logical judgment of an operand is false, you don’t need to continue.
| | : from left to right to judge, if found, the logic of an operand is true, then don’t continue to judge.
function fn (n1, n2) {
n1 = n1 || 0
n2 = n2 || 0
console.log(n1 + n2)
}
Copy the code
Switch-case branch structure
- 1. Grammar
switch(expression){// It is not a Boolean type: it is a definite variable
case 值1: // Value 1, value 2... It's all literalThe result of the expression === value1, the code to executebreak;
case 值2: Result of the expression === value2, the code to executebreak;
case 值3: Result of the expression === value3, the code to executebreak; .default: the result of the expression and all of the abovecaseIf the following values are not congruent, the code here is executedbreak;
}
Copy the code
- 2. Precautions
- 1. The result of an expression must be congruent with its value
- 2. Break function: To end the switch statement, it is usually added. Otherwise, it will break through
- Penetration: Faster execution from the previous case code to the next case code
- The break keyword is used to prevent penetration
- 3. The default statement can be written anywhere or omitted, but is usually written at the end. This is a code specification
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
/** switch-case branch structure: usually used for value matching * matching: congruent relation * switch(conditional value){case value 1: conditional value === value 1, the code to execute break; Case value 2: conditional value === value 2, need to execute the code break; Case value 3: conditional value === value 3, need to execute the code break; . Default: if the conditional value is not congruent with any of the above case values, this code break is executed; } /**switch statement note * 1. The result of the expression must be identical to the value of the statement === * 2. The default statement can be written anywhere or omitted, but is usually written at the end. This is a code specification */
// Example: 1- front-end 2-PHP 3- Java 4-UI
let subject= +prompt("Please enter the subject number you are applying for, 1-front-end 2-PHP 3-Java 4-UI");
switch (subject){
case 1:
alert("Congratulations on choosing 2020's most lucrative subject!");
break;
case 2:
alert("Chose PHP, you rogue!");
break;
case 3:
alert("Chose Java, how much is a hair transplant?");
break;
case 4:
alert("UI Visual Interaction Designers of the future");
break;
default :
alert("Brain bags.");
break;
}
</script>
</body>
</html>
Copy the code
Switch-case Usage penetration
- Reasonable penetration: Multiple values need to execute the same code
<script>
/** reasonable penetration: using penetration when there are multiple values that need to execute the same code saves code * the user enters a month and tells the user what season it belongs to * 12,1,2 winter * 3,4,5 spring * 6,7,8 summer * 9,10,11 fall */
let month = +prompt("Please enter month");
switch (month){
case 12:
case 1:
case 2:
alert("Winter");
break;
case 3:
case 4:
case 5:
alert("Spring");
break;
case 6:
case 7:
case 8:
alert("Summer");
break;
case 9:
case 10:
case 11:
alert("Autumn");
break;
default:
alert("Are you from Mars?");
break;
}
</script>
Copy the code
Ternary expression
-
1. Operators Are divided into unary, binary and ternary operators according to the number of values involved in the operation
- Unary operator: can operate on only one value ++ –!
- Binary operator: operates on two values 1 + 1 1 > 0
- Ternary operators: Operate on three values
-
2. Ternary operator syntax
-
Ternary operators:? :
-
Ternary expressions:
Bool expression? Code 1: Code 2Copy the code
- 1. Execute code 1 if the expression is true, otherwise execute code 2
-
-
2. If either code 1 or code 2 has a result, the result of the ternary is one of them
-
Ternary operators do the same thing as if-else, only the code is cleaner
-
In a ternary expression: the expression part is always a condition, and ultimately either code 1 or code 2 represents the entire result
-
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
<script>
/* Unary operator: a++ a--! A binary operator: operator involving two values: A + b A > b Ternary operator: operator involving three values */
/* * ternary operator:? : * Ternary expressions: expressions? Code 1: Code 2 * * 1. Execute code 1 if the expression is true, otherwise execute Code 2 * * 2. If code 1 or 2 has a result then the result of the ternary is one of their * * ternary operators that does the same thing as if-else, except that the code is simpler */
/ / case 1:
let num1 = 10;
num1 > 0 ? console.log('ha ha') : console.log('呵呵');
// The ternary expression above is equivalent to the if-else statement below
// if(num1 > 0){
// console.log (" ha ha ");
// }else{
// console.log (" hehe ");
// }
// Case 2: Ternary expressions are commonly used to assign values
let num2 = 20;
let res2 = num2 > 0 ? num2 + 1 : num2 - 1;
console.log ( res2 );/ / 21
// The ternary expression above is equivalent to the if-else statement below
// if(num2 > 0){
// res2 = num2 + 1;
// }else{
// res2 = num2 - 1;
// }
// Exercise: Output gender (in real development, gender is usually stored using a Boolean type, which is more efficient)
let name = "马云";
let age = 38;
let gender = true; //true male 1 false female 0
console.log("My name is."+name+"My age is."+age+"I am one."+(gender == true ? "Male":"Female") +"Raw");
</script>
</html>
Copy the code
Summary of three branch structure syntax
- 1. In principle, the three branch structure statements can be interchangeable, but each branch structure statement applies to different scenarios
- 2. If branch structure: suitable for condition judgment
- Most commonly used: if-else two mutually exclusive conditions
- 3. Switch-case is suitable for matching fixed values
- 4. Ternary expressions: more concise than if-else code, but less legible with more code. Later it has one of the biggest advantages: it can be added in templates
- The quotation marks
- A template engine
- Interpolation expression
While loop structure
- Three elements of circulation
- The starting value
- conditions
- Variation of variable
- 1. Grammar:
while(conditionstrue/false){body of loop/code that needs to be executed repeatedly; }Copy the code
- Execution steps:
- 1. Determine whether the condition is true
- 1.1 If true, execute the loop body code and repeat Step 1
- 1.2 If this is not true, end the loop and execute the code following the braces
- 1. Determine whether the condition is true
- 3. Pay attention to the point
- (1) The statement in parentheses, whatever the result is, will be converted to Boolean to determine whether it is true
- (2) Avoid writing an endless loop
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
// Needs: print 3 times' I love big front end '
// copy-paste disadvantages :(1) redundant code and (2) poor maintenance
// console.log (" I love big front-end ");
// console.log (" I love big front-end ");
// console.log (" I love big front-end ");
While (conditional true/false){loop body: code that needs to be executed repeatedly}; Perform Step 1. Check whether the condition is true. 2.1 Yes: Execute the loop body code. Repeat step 1 2.2 is not true, the loop statement ends, and the code */ following the braces is executed
let i = 1;// count the number of loops
while(i<=3) {console.log ( "I love the big front end" );
i++;//// The purpose of the loop variable increment and increment is to control the number of cycles that would otherwise be an infinite loop
}
console.log('111');// The code outside the braces has no relation to the loop structure and is executed sequentially
// loop statement:
// loop statement:
//(1) the statement in parentheses, whatever the result is, will be cast to Boolean to determine whether it is true
//(2) Avoid writing an endless loop
//let num = 1;
// while(num < 10){
// console.log ( num );
// num++; // Change the value of the loop variable to avoid endless loops
// }
</script>
</body>
</html>
Copy the code
Do -while loop structure
- 1. Grammar:
do{circulatory body; }while(conditions);Copy the code
- 2. Execution process
- 1. Execute the loop body code first
- 2. Execute the conditional statement
- If the result is true, the loop body code is executed
- If false, the loop ends
- 3. Repeat Step 2
- 3. Do -while and while implement the same loop, except for one difference: do-while executes the body of the loop anyway, and then evaluates the condition
- While loop: play before chopping (judge the condition before executing the loop body)
- Do-while loop: do first and then do later (execute the loop body code once anyway, then judge the condition)
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
/* 1. Learning objectives: do-while loop 2. Learning route (1) review while syntax features (2) learn do-while syntax (3) introduce do-while syntax application scenarios */
/ / while loop:
//let i = 1;
// while(i > 5){
// // the loop condition is not valid. The loop body is not executed once
// console.log (" ha ha ha ha ");
// i++
// }
/ / 2. The do while loop
/** do-while syntax :(rarely used) do{loop body; } while (conditions); Features: Execute the body of the loop once anyway, and then judge the condition */
let i = 1;
do{
console.log ( "Ho ho ho ho!" );
i++;
}while (i > 5);
// While loop: play first and then chop (judge condition first and then execute loop body)
//do-while loop: do first and then do later (execute the loop body code once anyway, then judge the condition)
//3. Do while loop and while loop application scenarios
// The body of the loop needs to be executed first anyway
// Example: ask the user to enter his/her account and password. If he/she enters correctly, he/she logs in successfully. If he/she enters incorrectly, he/she keeps typing
// While loop implementation
// let username = prompt(' please enter account ');
// let password = prompt(' please enter password ');
//
// while(username ! = 'admin' || password ! = '123456') {
// username = prompt(' please enter account ');
// password = prompt(' please enter password ');
// }
/ / do - while implementation
do{
let username = prompt('Please enter your account number');
let password = prompt('Please enter your password');
}while(username ! ='admin'|| password ! ='123456')
</script>
</body>
</html>
Copy the code
Summary of three cyclic structures
- 1. In principle, the three loop constructs can be interchangeable, but each statement applies to a different situation
- 2. Most commonly used: for loop: suitable for a fixed number of cycles
- 3. While loop: the number of cycles is not fixed
- 4. Do-while loop: The number of loops is not fixed, but the loop body code should be executed at least once
2- Array sort – bubble algorithm
- An algorithm, an algorithm, is a way to solve a problem
- Algorithm goal: use the least memory, the shortest time, to solve the most problems
- Bubble algorithm:
- The column of elements to be sorted is repeatedly visited, comparing two adjacent elements in turn
- Correct order: indicates that the position is correct and there is no need to swap
- Out of order: Swap two elements so that the order is correct
- The column of elements to be sorted is repeatedly visited, comparing two adjacent elements in turn
<script>
1. Starting with the first element, compare the next element * if the preceding element is greater than the following element: swap * if the preceding element is less than or equal to the following element: do not move 2. Loop over each element in the array until the largest element reaches the end of the array 3. A cycle, can only get the largest data row till the last (most) before, so we need according to the length of the array elements for a nested loop * a will only make the biggest in the end, if it's largest at the last, it is great) * according to the length of the array implementation: each time can get a maximum, until all sorted * /
// Define an unordered array
let arr = [3.5.1.8.6.2];
// External loop: determines the number of inner loops
for(let i = 0; i < arr.length; i++){// Inner loop: determines the current largest element to run to the correct position
for(let j = 0; j < arr.length -1; j++){// j < arr.length-1 because we need to match the elements back one
// Determine the relation between the current element and the next element: the former is greater than the latter: swap (otherwise unchanged)
if(arr[j] > arr[j+1]) {// Swap the values of two elements: take the third variable
let temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp; }}}console.log(arr); / /,2,3,5,6,8 [1]
</script>
Copy the code
3. Object-oriented programming
The basic concept
Object orientation is: you want to do something that you can’t do yourself, so find an object that can do it, call its methods (pass parameters, follow the rules of the method)
What is an object?
Everything is object
What an object really is can be understood at two levels.
(1) An object is an abstraction of something concrete.
A book, a car and a person can all be objects. When objects are abstracted into objects, the relationship between objects becomes the relationship between objects, so that the real situation can be simulated and the object can be programmed.
Q: Are books objects
(2) An object is an unordered collection of key-value pairs whose properties can contain base values, objects, or functions
Each object is created based on a reference type, which can be either a built-in native type or a developer custom type.
What is object orientation?
Object Oriented Programming, OOP for short, is a Programming development idea.
In the idea of object-oriented program development, every object is a function center, with a clear division of labor, can complete the task of receiving information, processing data, sending information. Therefore, object-oriented programming is flexible, reusable, highly modular and easy to maintain and develop. Compared with traditional procedural programming composed of a series of functions or instructions, it is more suitable for large-scale software projects with multiple people.
Object oriented and process oriented:
- Process-oriented is a way of thinking about problem solving. (Executor’s perspective)
- Focus on the process of solving the problem (first XX, then XX, in XX);
- Object orientation is to take an object and let her do it (from the director’s perspective)
- The focus is on finding the object that solves the problem.
- Object orientation is not a process – oriented replacement, but a process – oriented encapsulation
- For example, washing clothes (difference between procedural and object-oriented)
Object-oriented features:
- encapsulation
- To encapsulate the concrete implementation of functions inside the object, the outside world only needs to pay attention to how to use the methods provided by the object, and does not need to care about the concrete implementation of the object, this is encapsulation.
- inheritance
- In JS, the concept of inheritance is very simple, an object does not have some attributes and methods, another object has, take over to use, to achieve inheritance.
- Note: In other languages, inheritance is a relationship between classes; in JS, it is a relationship between objects.
- [Polymorphism]
- Polymorphism is only found in strongly typed languages. Js is a weakly typed language, so JS does not support polymorphism
4. The stack and the heap
The stack mainly stores some basic types of variables and object references. Its advantage is that the access speed is faster than the heap, but the disadvantage is that the size and lifetime of data in the stack must be determined, which lacks flexibility.
Heap is used to allocate space for complex data types (reference types), such as array objects and object objects. It allocates memory dynamically at runtime, so access is slow.
Stack and heap legend
-
Value type: a simple type in which a variable is stored as the value itself. If passed as a parameter, only a copy of the contents stored in stack space is assigned, and changing one of the variables does not change otherwise
-
Reference type: complex type. When a variable is stored, it stores the address of the object. If passed as a parameter, it copies the address of the reference stored in the stack space and assigns the value, causing the argument and parameter to point to the same space
5. Several ways to create objects
Built-in constructor created
We can create it directly with new Object() :
// In JS, objects have dynamic properties. You can add or delete properties to an object at any time.
var person = new Object()
person.name = 'Jack'
person.age = 18
person.sayName = function () {
console.log(this.name)
}
Copy the code
Cons: Cumbersome, each attribute needs to be added.
Object literal creation
var person = {
name: 'Jack'.age: 18.sayName: function () {
console.log(this.name)
}
}
Copy the code
Cons: What if you want to generate multiple objects in batches? The code is redundant
Simple improvement: Factory functions
We can write a function to solve the code duplication problem:
function createPerson (name, age) {
return {
name: name,
age: age,
sayName: function () {
console.log(this.name)
}
}
}
Copy the code
Then generate the instance object:
var p1 = createPerson('Jack'.18)
var p2 = createPerson('Mike'.18)
Copy the code
Disadvantages: But it does not solve the problem of Object recognition, created objects are Object type.
Continue to improve: constructors
The constructor is a function that instantiates an object and needs to be used with the new operator.
function Person (name, age) {
this.name = name
this.age = age
this.sayName = function () {
console.log(this.name)
}
}
var p1 = new Person('Jack'.18)
p1.sayName() // => Jack
var p2 = new Person('Mike'.23)
p2.sayName() // => Mike
Copy the code
To create a Person instance, you must use the new operator. Calling the constructor in this way goes through four steps:
- Create a new object
- Assign the constructor’s scope to the new object (so this refers to the new object)
- Execute the code in the constructor
- Return a new object
Constructors need to be used with the new operator to make sense; constructors usually start with a capital letter
Disadvantages of constructors
The biggest benefit of using constructors is that they make it easier to create objects, but there is a problem of wasting memory:
function Person (name, age) {
this.name = name
this.age = age
this.type = 'human'
this.say = function () {
console.log('hello ' + this.name)
}
}
var person1 = new Person('lpz'.18)
var person2 = new Person('Jack'.16)
console.log(person1.say === person2.say) // => false
Copy the code
Solution:
graphic
Solution: Extract the samesay
methods
- Solved the problem of wasting memory
- But caused
Pollution global variable
The problem of
// Declare say well in advance
function say() {
console.log(this.name);
}
function createStudent(name, age) {
this.name = name;
this.age = age;
this.say = say
}
const obj = new createStudent("One can".83);
const obj1 = new createStudent("One can 1".84);
console.log(obj.say === obj1.say); // true
Copy the code
graphic
6. Three ways to define functions
- Function declaration
- Functional expression
- Constructor Function
Function declaration
The conventional way
fn();// Function declaration can be called first, before declaration
function fn(Parameter..){
console.log("This is a function declaration.")
returnThe return value}Copy the code
Functional expression
const fn = function() {
console.log("This is a function expression.");
}
fn();// Function expressions must be declared before being called
Copy the code
Constructor Function
All functions can be created using the Function constructor
Functions can also be thought of as objects
New Function([preceded by argument list,] last argument is Function body)Copy the code
var fn1 = new Function("a1"."a2"."alert(a1+a2)");
fn1(1.2);
Copy the code
**