1. Process control statements

1. Basic use of the if statement

1. The if statement is the simplest conditional statement, also known as a select statement. It is usually used in conjunction with else to indicate if…… Just… Otherwise…

If statement example 1:

The user enters a number, if the number is even, the pop-up dialog box displays “even”, otherwise, the pop-up dialog box displays “odd”.

var n = Number(prompt('Enter a number :'));
    if (n % 2= =0) {
      alert(n+'Is an even number'.);
    }
    else {
      alert(n+'is an odd number'.);
    }
Copy the code

2. If statement execution flowchart

3. If statement Example 2

Users enter their age to determine whether they can apply for a driver’s license. To get a driver’s license, you must be between 18 and 70 years old.

var age=Number(prompt('Please enter age'));
    if(age>=18 && age<=70){
      alert('You are old enough to apply for a driver's license');
    }else {
      alert('You are not old enough to get a driver's license');
    }
Copy the code

Else: Else can be omitted in an if statement.

5. Identify which statements are in the if body.

6. Single-line IF statement: If the body of the IF statement contains only one line, you can omit braces and newlines.

If else if multi-conditional branch

1. For example: Users input test scores and output their grades according to the following table.

score The grade of
85-100. good
70-84. good
60-69. Pass the
0-59 Don’t pass the

Note the “otherwise if” : else if() condition branch “implies” does not meet all the previous conditions. Understand what “otherwise if” means.

2. Small case: calculation of BMI obesity index

The Body Mass Index (BMI) is calculated by dividing your weight in kilograms by your height in meters. It is an international standard used to measure how thin you are and how healthy you are.

BMI step
Less than 18.5 Too thin
18.5-24 (exclusive) normal
24-28 (exclusive) obese
28-32 (exclusive) obesity
At least 32 Very fat

3, if statement algorithm

A daffodil number is a three-digit number in which the cube sum of each digit is equal to itself.

2. Amusement park ticket calculation

The ticket price of an amusement park is shown in the table below. Ask the user to input the age and the day of the week, the pop-up dialog box shows the ticket price. The days of the week are represented by Arabic numerals 0, 1, 2, 3, 4, 5, and 6, where 0 is Sunday.

Age 10 years or older Younger than 10 years old
On weekdays 300 140
Over the weekend 500 210

Nesting of if statements is required:

4. Switch statement

1. The switch statement is used when a variable is being classified.

Inside the parentheses of switch() is usually a variable name, which will be discussed by category.

Case means “case” and is followed by a value without parentheses. The program in turn aligns the values following the case with those in the switch parentheses, and if the aligns are the same, the statement following the case colon is executed. Default: indicates the default value.

Multiple cases can share the same statement body.

Unlike the if statement, which automatically breaks out of the if statement after executing a branch, the programmer must actively call break to break out of the switch statement. If a break is not written, all subsequent cases are considered matches until a break is encountered.

3. For example, you are required to enter any number from 1 to 12 to display the number of days in the month.

5. Ternary operators (very common at work)

1.Javascript provides a syntactic form called “ternary operations” that makes it easy to implement select conditional expressions? Expression 1: expression 2

2. A question mark is preceded by a criterion, and two expressions are separated by a colon. Expression 1 is called when the conditional expression is true and expression 2 is called when the conditional expression is false.

3. The purpose of the ternary operator is to select the value of a variable between two different values depending on whether a condition is true or not.

6. The for loop

1. You can use a for loop to simplify your program

3. Exercise: Use the for loop to print 18, 14, 10, 6, 2, -2, -6 line by line on the console.

4. For loop

Calculation of 1 + 2 + 3… And + 99 + 100.

From 1 to 100, which number divided by 3 has a remainder of 1, divided by 4 has a remainder of 2, and divided by 5 has a remainder of 3?

7. The while loop statement

1. The while statement is also a loop structure. It is an “indeterminate range” loop and has different uses for the for loop.

The while statement does not specify in advance where the loop begins or ends. The loop body is executed as long as the test condition is satisfied.

2. While loop considerations

The while loop does not explicitly define loop variables. You must define loop variables outside of the while loop, sometimes without loop variables.

The statement in the loop body must make the loop test condition tend not to be true, otherwise the loop will be dead

3. More suitable for the scenario of a while loop: find the smallest integer n satisfying n2>456789 when no condition is found.

The rabbit pulls the turnip, 1 on the first day, 2 on the second day, 3 on the third day, and so on. How many days can the rabbit pull out 500 radish light? (There is a “mistake”)

8. Break and continue

1. Break: immediately terminates the loop. It can only be used in loop statements.

2. Break is used in while statements, usually with while(true){}.

3. Continue skips an iteration in the loop and continues to the next iteration in the loop. Continue is more often used for loops.

9. Do while loop

1. The do while loop is a post-test loop statement. It is different from the for loop and while loop, which each time “test the condition and then execute the body”, do-while loop, which “execute the body and then test the condition”.

2. The do-while loop writes the condition to the end of the body of the loop, so that the body must execute at least once before checking if the condition is true and deciding whether to continue.

3. Please write a program to randomly generate two variables dx and dy, which are randomly valued in the interval [-4,4], but require that dx and dy cannot be 0 at the same time. (Random number)

4. While statement algorithm

Figure guessing mini game: generate a random number from 2 to 99 and ask the user to guess what the number is. After the user enters his guess, the user is prompted “the number entered is too large” or “the number entered is too small”. Repeat the process until the user guesses the number accurately.

10. Random number function

1. Learn random number functions first. Get the decimal between o and 1: math.random ().

ParseInt (math.random () *(b – a + 1)) + a

11, algorithm

1. Algorithm refers to an accurate and complete description of problem solving scheme, as well as a series of clear instructions to solve problems. Algorithm represents the strategy mechanism to solve problems in a systematic way. In other words, the required output can be obtained in a limited time for a given specification of the input.

2. An algorithm is a problem broken down into steps that a computer can perform step by step.

3. The flow control statements of the computer: sequential execution, selection statement, circular statement.

4. Requirements of a good algorithm: correctness, robustness and readability.

5. Pseudo code

Calculation of 1 + 2 + 3 +… + 99 + 100 and:

(1) Define variable sum; (2) Go through the number from 1 to 100, denoted by I; Add each number I to sum; (3) Print and display sum.

12. Accumulator and multiplier

1. Enter the number n and calculate the value of the following formula

2. Enter the number N and calculate the factorial of n.

3. Use both accumulator and multiplicator

13, exhaustive method

1. The exhaustive method, as its name implies, is to determine the general scope of the answer according to the conditions of the question and verify all possible cases one by one within this scope until all cases are verified. If a case satisfies the conditions of the problem, it is a solution of the problem; If all the conditions are not met after verification, there is no solution in this problem.

2. Example: Program to find the number up to 100 that is divisible by both 3 and 5.

3. Example: The user enters a number and all divisor of the number are displayed on the console.

4. Find all the daffodils. A daffodil number is a 3-digit number in which the cube sum of each digit is equal to itself.

14. Comprehensive algorithm

1. Nesting of loops

2. Find all prime numbers from 1 to 100

3. There were 35 heads on the top and 94 feet on the bottom of a cage with a pheasant rabbit

15. Focus of the course

1. What are the flow control statements in JavaScript?

2. Execution mechanism of if multi-branch statements; The execution mechanism of the for loop

3. What are the usage scenarios for and while loops?

16. Difficult points

1. The idea of accumulator and multiplicator and exhaustive algorithm

2. Various algorithms

3. Take what you have learned in this lesson and integrate it into the rest of the lesson

Second, the array

1. Introduction and definition of arrays

1. An Array, as its name implies, is used to store a set of related values for easy summation, average calculation, item by item traversal, etc.

2. Array definition method 1: Defining an array is very simple, just use square brackets []. var arr =[ ‘A’,’B’, ‘c’, ‘D’];

Var arr = new Array (‘A’, ‘B ‘,’C ‘,’D’);

Array definition method 3: The following code defines an array of length 4, but all 4 items are undefined. var arr =new Array(4);

3. Access array items:

Each item in the array has a subscript that starts at 0.

You can access any item in the array using subscripts written in square brackets.

4. Subscript out of bounds: JavaScript states that accessing items that do not exist in an array will return undefined without error.

5. Length of array: The length property of an array indicates its length. The index of the last item in the array is the length of the array minus 1.

6. Change an array item: An array is not read-only, and you can change the value of any item in it. This item is created if the changed array item exceeds Length-1.

 var arr=['i'.'m'.'o'.'o'.'c'];

  arr[2]=arr[2].toUpperCase();

  arr[6] ='A';

  console.log(arr);

// (7) [' I ','m','O',' O',' c', 'A']
Copy the code

7. Array traversal: Arrays have the advantage of being easy to traverse.

for(var i=0; i<arr.length; i++){console.log(arr[i]);
    }
//(7) ["i", "m", "O", "o", "c", empty, "A"]
Copy the code

If you type several commas in the middle of the array, the output will show undefined.

2, array type detection

1. Array typeof detection result is Object.

The array.isarray () method can be used to detect arrays.

3. Common methods for arrays

1. Array header and tail operations

methods function
push() Insert a new item at the tail
pop() Delete at the tail
unshift() Insert a new item in the header
shift() Delete in the header

The (1) push() method is used to push a new item at the end of the array, and the parameter is the item to push.

If you want to push multiple entries, separate them with commas.

The array changes immediately after the push() method is called, without assignment.

(2) In contrast to push(), the pop() method is used to remove the last item in the array. The pop() method not only removes the last item of the array, but also returns the deleted item.

(3) The unshift(() method is used to insert new items at the beginning and end of the array. The parameter is the item to insert.

If you want to insert multiple entries, separate them with commas. When the unshift() method is called, the array changes immediately, without assignment.

Instead, the shift() method is used to remove items with subscript 0 from the array.

The shift() method not only deletes the first item of the array, but also returns the deleted item.

2. Splice () method (1) The splice() method replaces the specified item in an array.

var arr=[0.1.2.3.4.5];
arr.splice(3.2.66.77.88.99);
// Selects two consecutive items, starting with the array with subscript 3, and replaces them with the following parameters
//(8) [0, 1, 2, 66, 77, 88, 99, 5]
Copy the code

(2) The splice() method can be used to insert new items at the specified location.

var arr=[0.1.2.3.4.5];
arr.splice(2.0.44.55.66.77);
// Start with the array with index 2, insert the next 4 items without replacing the number in the array
//(10) [0, 1, 44, 55, 66, 77, 2, 3, 4, 5]
Copy the code

(3) The splice() method can be used to delete the specified item.

var arr=['apple'.'"'.'watermelon'.'Peach'];
arr.splice(2.1);
// Delete one item from the array with index 2
//[" apple ", "pear "," peach "]
Copy the code

(4) The splice() method returns the deleted item as an array

var arr=[0.1.2.3.4.5];
items=arr.splice(3.2.66.77.88.99);
console.log(arr);
console.log(items);
//(8) [0, 1, 2, 66, 77, 88, 99, 5]
/ / (2) (3, 4]
Copy the code

3. The slice () method

The slice() method is used to get subarrays, similar to the slice() method of strings.

Slice (a, b) intercepts subarrays starting with items with subscript A and ending with items with subscript B (but excluding items with subscript B). The Slice (a,b) method does not change the original array.

Slice (), if it does not provide a second argument, extracts all subsequent items as subarrays, starting with the specified item.

Arguments to the slice() method are allowed to be negative, indicating the penultimate item of the array

var arr=['A'.'B'.'C'.'D'.'E'.'F'];
var child_arr1=arr.slice(2.5);
//(3) ["C", "D", "E"]
Copy the code

4. Join () and split() methods: The join() method of an array converts an array to a string; The split() method of a string converts a string to an array.

The arguments to join() indicate what character is used as the join character. If left blank, they are separated by commas by default, as if toString() was called. The split() argument indicates what character to split the string with, and generally cannot be left blank.

Strings can also be written in square brackets, and accessing a character is equivalent to the charAt() method.

Some algorithmic problems with strings are sometimes solved by converting them to arrays

The concat() method can merge and concatenate multiple arrays. The concat() method does not alter the original array.

7. Reverse () method (only arrays can be called)

The reverse() method is used to invert all items in an array.

arr.reverse();

8. The indexOf() and includes() methods search for an element in an array and return its location, or -1 if none exists. The includes() method determines whether an array contains a specified value, returning a Boolean value.

['A'.'B'.'C'.'D'.'E'].indexOf('C')
/ / 2

['A'.'B'.'C'.'D'.'E'].includes('D')
//true
Copy the code

9. About sorting arrays: There is a sort() method for sorting arrays.

4. Traverse the correlation algorithm

1.题目: find the sum and average of each item in the array.

2.题目: find the maximum and minimum value of an array item.

5. Array de-duplication and random samples

1. Array deduplicating:

Remove duplicates from an array.

Prepare an empty result array, iterate through the original array, if the iterated item is not in the result array, push the result array.

2. Random sample

Please select 3 items randomly from the array

Prepare an empty array of results, iterate over the array, select an item at random, push it into the array, and delete the item.

6. Bubble sort

1. Bubble sort is a famous sorting algorithm, but also in the interview very love to investigate the algorithm.

The idea behind bubble sorting is to do a series of pairwise comparisons, each time arranging the smallest element in its place, like bubbles floating in water.

2. N numbers need to be compared n(n-1)/2 times.

for(var i=1; i<arr.length; i++){for(var j=arr.length-1; j>=i; j--){if(arr[j]<arr[j-1]) {var temp=arr[j];
          arr[j]=arr[j-1];
          arr[j-1]=temp; }}Copy the code

7. Two-dimensional arrays

1. Two-dimensional arrays: Arrays with arrays as array elements, i.e., “arrays of arrays”.

2. Two-dimensional arrays can be thought of as matrices.

8. Base and reference type values

1. Base and reference types

Basic types :number, Boolean, string, undefined, null

Reference types: array, Object, function, regexp…

2. Differences in equality Judgment Basic types Compare values for equality. When a reference type makes an equality determination, it compares addresses for equality, that is, it compares for the same thing in memory.

3. Summary

For example, When var a = b is passed When you compare with ==
Base type value Numeric, string, Boolean, undefined A new copy is generated in memory Compares whether the values are equal
Reference type value Objects, arrays Instead of creating a new copy in memory, a new variable points to the same object Compares whether memory addresses are equal, that is, whether they are the same object

Deep cloning and shallow cloning

1. Shallow clones of arrays are not cloned using arr1=arr2 syntax: only the first layer of an array is cloned. Other layers are not cloned if the array is multi-dimensional or if the items in the array are values of other reference types. Deep clone: Clone all the layers of an array, using a recursive technique described later in the lesson.

10. Important knowledge points

1. What is an array? How should it be defined?

2. How do I detect array types?

3. What are the common methods of arrays?

11. Difficult knowledge points

1. Array traversal correlation algorithm, deduplication and random sample, bubble sort.

2. The difference between base type values and reference type values.

3. Implement shallow cloning