8. Array
1. Create an array using array literal: with a square bracket
var array name = []// Create an empty array
var array name = [1,2, 'year', ture]// Create an array with initial values using array literals
2. Type of array element: the array can hold any type of data
3. Get / access array elements through array name [index]
Index starts at 0
4. Obtain the array length through the array name. Length
Array length refers to the number of elements
5. Traversal array
Is to access the elements of the array from beginning to end
Column 1:
<script> // Find the maximum value in the array [3,5,6,7,0] // 1. Declare a variable max that holds the largest element // 2. The default maximum value is the first element in the array // 3. Traverse the array, that is, compare each array element with max. if it is larger than max, save it in max var arr= [3,5,6,7,0]; var max=arr[0]; for(var i=1;i<arr.length;i++){//Here, starting with the second element, the index is 1 if(arr[i]>max){ max=arr[i]; } } console.log('Maximum element:'+max); </script>
6. New element in array
1. Add an array element by modifying the length of length
The default value of new array elements is undefined
<script> var arr= [3,5,6,7,0]; arr.length=10;//length is readable and writable console.log(arr);//Directly outputting the array name will get all the elements in the array console.log(arr[6]);//undefined, that is, to access a variable that is declared but not assigned a value </script>
2. Add an array element by modifying the index number
In the previous example, you can:
arr[5]=10;
3. Case 1: filter array
<script> // Requirements: select the elements greater than or equal to 10 in the array [3,5,6,7,0,20,30,21] and put them into the new array // 1. Declare a new array to store elements greater than or equal to 10 // 2. Traverse the array to find elements greater than or equal to 10 // 3. Add to the new array newArr in turn, using the hump naming method var arr = [3, 5, 6, 7, 0, 20, 30, 21]; var newArr = []; var j = 0; for (var i = 0; i < arr.length; i++) { if (arr[i] >= 10) { newArr[j] = arr[i];//The new index number starts from 0, sets a new variable j, and increments from 0 j++; } } console.log(newArr); </script>
4. Case 2: delete the specified array element
<script> // Requirement: remove the 0 element from the array [3,5,6,7,0,20,30,21] and put it into a new array // 1. Declare a new array to store the elements after deleting 0 // 2. Traverse the array to find elements that are not 0 // 3. Add to the new array newArr in turn, and the length of the array is continuously accumulated var arr = [3, 5, 6, 7, 0, 20, 30, 21]; var newArr = []; for (var i = 0; i < arr.length; i++) { if (arr[i]!= 0) { newArr[newArr.length] = arr[i]; //The new index number starts from 0 and newArr.length increases successively from 0 } } console.log(newArr); </script>
7. Flip array
<script> // Requirement: store the elements in the array [3,5,6,7,0] in reverse and output [0,7,6,5,3] // 1. Declare a new array to store the elements stored in turn // 2. Take the 4th index number of the old array (arr.length-1) and give the 0th element of the index number of the new array (newArr.length) // 3. The index in the old array is decremented and appended to the new array newArr in turn var arr = [3, 5, 6, 7, 0]; var newArr = []; for (var i = arr.length-1; i >=0; i--) { newArr[newArr.length] = arr[i];//The new index number starts from 0 and newArr.length increases successively from 0 } console.log(newArr);//obtain [0, 7, 6, 5, 3] </script>
8. Bubble sorting of array elements
First, swap two variables and introduce a temporary variable
Bubble sort: compare two elements at a time, and exchange them if they are in wrong order
For example, 4, 5, 2, 1 and 3 should be sorted from small to large
The first trip: 4, 2, 1, 3, 5 exchanged 4 times
Compare 4 and 5 first, and do not exchange;
5 and 2, exchange;
5 and 1, exchange
5 and 3, exchange
The maximum value is 5, which has been found. You will no longer participate in the comparison below
The second trip: 2, 1, 3, 4, 5// Found 4 and 5 and exchanged 3 times
The third time: 1, 2, 3, 4, 5 / / find 3, 4, 5 and exchange them twice
The fourth trip: 1, 2, 3, 4, 5 / / 2, 3, 4, 5 are found and exchanged once
Bubble sort end
Discovery:
- The total number of trips required is implemented with outer layer for
The five data go four times, and the number of times is equal to the length of the array minus 1
2. The number of times of each exchange is realized by the inner layer for
Number of times + times = length of array
However, the number of times should start from 0, so the initial value of the number of times = arr.length-i-1
<script> var arr=[4,5,2,1,3]; for(var i=0;i<arr.length;i++){ for(var j=0;j<=arr.length-i-1;j++){ //In ascending order, the previous value is compared with the latter value. If it is greater than the latter value, it is exchanged if(arr[j]>arr[j+1]){ var t=arr[j]; arr[j]=arr[j+1]; arr[j+1]=t; } } } console.log(arr);// [1, 2, 3, 4, 5] </script>
9. Function
1. Use of functions: declaring and calling functions
1. Declaration function: function function name () {}
Function is the keyword to declare a function and must be lowercase. Generally, the function name is named with verbs. For example, getSum, don't forget to use the hump naming method
2. Calling function: function name ();
Functions are not called and are not executed by themselves
script> //Summation function function getSum(){ var sum=0; for(var i=1;i<=10;i++){ sum+=i; } console.log(sum); } getSum(); </script>
2. Parameters of function
- Function function name (formal parameter) {}
- Function names (arguments) pass arguments to formal parameters
<script> //Find the sum function between two numbers function getSum(start,end){ var sum=0; for(var i=start;i<=end;i++){ sum+=i; } console.log(sum); } getSum(1,100);//5050 </script>
3. Matching between formal parameters and arguments: (generally, the number of arguments is equal to the number of formal parameters)
1. If the number of arguments is equal to the number of formal parameters, the result will be output normally
2. If the number of arguments is greater than the number of formal parameters, get the number of arguments according to the number of formal parameters
3. If the number of arguments is less than the number of formal parameters, the extra formal parameters are defined as undefined, and the final result is NaN
<script> function getSum(a,b){ console.log(a+b); } getSum(1,100,20); //101 getSum(1);//NaN </script>
3. Return value of function
- Use the return statement to return the return value of the function to the caller: function name ()
<script> // Find the maximum of two numbers function getMax(num1, num2) { return num1 > num2 ? num1 : num2; } console.log(getMax(1, 3)); </script>
- A variable is often used to receive the return value of a function
- return stop function
The code after the return statement in the function body is not executed - Return can only return one value. If multiple values are separated by commas, the last one shall prevail
If you want to return multiple values at the same time, you can return an array, and then traverse the array to get the elements in the array
<script> // Find the addition, subtraction, multiplication and division of two numbers function getRsult(num1,num2){ return [num1+num2,num1-num2,num1*num2,num1/num2] } var re=getRsult(1,3); console.log(re);//[4, -2, 3, 0.3333333333333333] </script>
- All functions have a return value. If there is a return, the value after return will be returned;
If there is no return, it returns undefined;
4. Use of arguments
-
In JS, arguments is a built-in object of the current function. All functions have a built-in arguments object, which stores all the arguments passed
-
arguments is a pseudo array
1. Have the length attribute of the array
2. Store all passed arguments in the way of index
3. It doesn't have some methods of real array, such as pop() push(), etc -
code:
<script> function fn(){ console.log( arguments); //Arguments(4) [1, 2, 4, 5, callee: ƒ, Symbol(Symbol.iterator): ƒ] console.log( arguments.length);//4 console.log( arguments[1]);//2 } fn(1,2,4,5); </script>
Only functions have arguments objects. Each function has built-in arguments objects, which can be used directly
<script> // Using function to find the maximum value of any number function getMax(){ var max=arguments[0]; for(var i=1;i<arguments.length;i++){ if(arguments[i]>max){ max=arguments[i]; } } return max; } console.log(getMax(1,5,6,7,3));//7 console.log(getMax(1,5,6,7,8,0));//8 </script>
5. Use the function to flip the array
<script> function reverse(arr) { var newArr = []; for (var i = arr.length - 1; i >= 0; i--) { newArr[newArr.length] = arr[i]; //The new index number starts from 0 and newArr.length increases successively from 0 } return newArr; } var arr1 = reverse([3, 5, 6, 7, 0]); console.log(arr1);//[0, 7, 6, 5, 3] var arr2 = reverse([3, 5, 4, 4, 2, 6]); console.log(arr2);//[6, 2, 4, 4, 5, 3] </script>
5. Use the function to sort the array: bubble sort
<script> // Bubble sort array function sort(arr) { for (var i = 0; i < arr.length; i++) { for (var j = 0; j <= arr.length - i - 1; j++) { //In ascending order, the previous value is compared with the latter value. If it is greater than the latter value, it is exchanged if (arr[j] > arr[j + 1]) { var t = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = t; } } } return arr; } var arr1 = sort([4, 5, 2, 1, 3]); console.log(arr1); //[1, 2, 3, 4, 5] var arr2 = sort([3, 9, 6, 5, 3, 2, 1]); console.log(arr2); //[1, 2, 3, 3, 5, 6, 9] </script>
6. Judge leap year
<script> // If yes, return true for leap years and false for normal years function isRunYear(year){ var flag=false; if(year%4==0&&year%100!=0||year%400==0){ flag=true; } return flag; } console.log(isRunYear(2000));//true console.log(isRunYear(1999));//false </script>
7. A function calls another function. A function is a code block that implements a function
<script> // Requirement: the user inputs the year and outputs the number of days in February of the current year // Analysis: if it is a leap year, February is 29 days; If it is a normal year, February is 28 days function backDay() { var year = prompt('Please enter the year: '); if (isRunYear(year) == true) { alert('The current year is a leap year,2 The month has 28 days'); } else { alert('The current year is a normal year,2 The month has 29 days'); } } backDay(); //Function to judge whether it is a leap year: // If yes, return true for leap years and false for normal years function isRunYear(year) { var flag = false; if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { flag = true; } return flag; } </script>
8. Function declaration:
- Using the function keyword function function name () {} is called a named function
Calling function: function name (); - Using function expressions:
var variable name = function() {}
Calling function: variable name ();
1. When declaring, it is a variable name, not a function name. This function has no name and is called an anonymous function
2. Similar to declaring variables
3. You can also pass arguments to formal parameters
10. Scope: divided into global scope and local scope
- Global scope: generally refers to the entire script tag or a separate js file
- Local scope: refers to the scope that only works inside the function
- Due to different scopes, variables are also divided into global variables and local variables
Note: if there is no var declaration inside the function, the directly assigned variable is also a global variable
The formal parameters of a function are local variables - Global variables are destroyed only when the browser is closed, which takes up more memory
Local variables are destroyed when the program is executed, which saves memory - Scope chain: when nested functions are used, the internal function can access external function variables. The chain search is used to determine which data can be accessed by internal functions, which is called scope chain
From the visited place, look up layer by layer and follow the principle of proximity
<script> var num=10;//global variable function fn1(){ var num=20;//local variable function fn2(){ console.log(num);//20 // Looking up layer by layer, we found the local variable var num=20; } } </script>
Summary: when internal functions access variables of external functions, the principle of proximity shall be adopted