function
The definition of Js function: encapsulates a code block that can be repeatedly executed and called.
Purpose: Allow a lot of code to be reused
Function experience
Sum of functions
The naming of the function name is a verb, and the naming of the variable name is a noun
<script>
function getSum(num1, num2) {
var sum = 0;
for (var i = num1; i <= num2; i++) {
sum = sum + i;
}
return sum;
}
console.log(getSum(1, 100)); //求~100的和
console.log(getSum(1, 1000)); //求1~1000的和
</script>
Use of functions
- Declare function
- Call functions
Declare function
function 函数名() {
//函数体
}
Call functions
函数名()
Precautions
- function is a keyword to declare a function, so it must be lowercase
- Function is to do something, so the name of the function is a verb
- The function itself is not executed, it must be called to execute
- Don't forget to add parentheses when calling
Simple use of functions
<script>
//声明函数
function sayHi() {
return '尧子陌'
}
//调用函数
console.log(sayHi())
</script>
Encapsulation of functions
Simply put, it is to encapsulate one function and multiple functions in the form of functions, and provide a simple function interface to the outside.
Simple understanding: similar to express packaging
The encapsulation of the function finds the cumulative multiplication between 1~10
<script>
function getSum(num1, num2) {
var sum = 1;
for (var i = num1; i <= num2; i++) {
sum = sum *i;
}
return sum;
}
console.log(getSum(1, 10)); //求~10的相乘的结果
</script>
Function parameters
- The parameters of the function: the form participates in the actual parameter
- When declaring a function, the parameters in the parentheses after the function name are called formal parameters. The formal parameters are formal parameters and are used to receive the values passed by the actual parameters.
- When calling a function, the parameters in parentheses after the function name are called actual parameters.
- The value inside the function is uncertain, and different values can be passed in through the actual parameters
- The parameters of the function are optional
Function case
The sum of any two numbers in a function case
<script>
// 声明函数
function getSum(num1, num2) {
return num1 + num2
}
//调用函数
console.log(getSum(100, 200))
console.log(getSum(10, 20))
</script>
Function case to find the sum between any two numbers
<script>
//声明函数
function getSum(star, end) {
var sum = 0;
for (var i = star; i <= end; i++) {
sum = sum + i;
}
return sum
}
//调用函数
console.log(getSum(20, 50))
console.log(getSum(1, 100))
</script>
The shape of the function participates in the matching of the number of arguments
When the number of the function's formal participation and actual parameters is the same
If the number of function parameters is the same, the input result is normal
<script>
//声明函数
function getSum(num1, num2) {
return num1 + num2
}
//调用函数
console.log(getSum(10, 20))
</script>
When the number of actual parameters of a function is greater than that of formal parameters
The number of function formal parameters is less than the number of actual parameters, then the number of formal parameters shall prevail
<script>
//声明函数
function getSum(num1, num2) {
return num1 + num2
}
//调用函数
console.log(getSum(1, 200, 500))
</script>
When the formal parameters of the function are greater than the actual parameters
The number of function parameters is greater than the number of actual parameters, the result is NaN
Precautions
- The formal parameters of the function can be regarded as unassigned variables, and the value is undefined;
- Add any value to undefined, the final result is NaN (not a number)
<script>
//声明函数
function getSum(num1, num2, num3) {
return num1 + num2 + num3
}
//调用函数
console.log(getSum(100, 200)) //形参的个数大于实参的个数的情况下
console.log(getSum(100, 200, 500)) //形参的个数与实参的个数一致的情况下
</script>
Summary of function parameters
- Function can take parameters or no parameters
- When the function has multiple parameters, separated by a comma in English
- When declaring a function, the parameters in the parentheses after the function are formal parameters, and the default value is undefined
- When calling a function, the parameters in parentheses after the function are actual parameters
- The form and actual parameters of the parameters should be consistent, otherwise the result is difficult to predict.
The return value of the function
The function is to achieve a certain thing or a certain function, and eventually return the return value to the caller of the function.
During the execution of the function, when return is encountered, the result will be returned to the caller of the function.
<script>
//声明函数
function getResult() {
return 520
}
//调用函数
console.log(getResult())
</script>
The return value of the function finds the maximum value between two numbers
The first type: use the if statement
<script>
function comParison(num1, num2) {
if (num1 > num2) {
return num1
} else {
return num2
}
}
console.log(comParison(20, 50))
</script>
The second type: use ternary expressions
<script>
function comParison(num1, num2) {
return num1 > num2 ? num1 : num2
}
console.log(comParison(20, 50))
</script>
The return value of the function finds the maximum value of the array
In actual development, variables are usually used to receive the return value of the function
<script>
function getMax(arr) {
var max = arr[0]
for (var i = 0; i < arr.length; i++) {
if (max <= arr[i]) {
max = arr[i]
}
}
return max;
}
var result = getMax([5, 10, 52, 38, 98,69]);
console.log(result);
</script>
return
return: termination function
The statement after return will not be executed
<script>
function getSum(num1, num2) {
return num1 + num2;
alert('hello word')
}
getSum(10, 20);
console.log(getSum(10, 20));
</script>
Only one value can be returned after return
<script>
function fn(num1, num2) {
return num1, num2
}
console.log(fn(20, 50));
</script>
The use of return array can return multiple values
<script>
function fn(num1, num2) {
return [num1 * num2, num1 / num2, num1 - num2, num1 + num2]
}
console.log(fn(20, 50));
</script>
The difference between break continue return
- break: end the current loop
- continue: End the current loop and continue to the next loop
- return: If you do not enter, you can jump out of the loop and end the code in the function body, and return the result to the caller of the function
See through the function through the juicer
Use of arguments
When we are not sure how many actual parameters there are, we can use the arguments object, which is a built-in object of the function and stores all the passed actual parameters.
<script>
function fn() {
for (var i = 0; i < arguments.length; i++) {
console.log(arguments[i]);
}
}
fn(5, 20, true, false, '李小龙', '张飞');
</script>
Precautions
- arguments is a pseudo-array, not an array in the true sense
- Arguments have a length attribute and are sorted by index
- Arguments cannot use real array methods, such as push, pop
Use arguments to find the maximum value in the array
Idea: The idea of finding the maximum value of an array is the same
<script>
function fn() {
//声明一个最大值变量max
var max = 0;
for (var i = 0; i < arguments.length; i++) {
if (max < arguments[i]) {
max = arguments[i]
}
}
return max
}
var result = fn(2, 5, 15, 20, 25, 85, 55, 64);
console.log(result);
</script>
Function packaging case
Flip arbitrary array in function package case
<script>
function reserve(arr) {
var newArray = [];
for (var i = arr.length - 1; i >= 0; i--) {
newArray[newArray.length] = arr[i]
}
return newArray;
};
console.log(reserve([20, 50, 60, 80, 100]));
</script>
Function encapsulation to achieve bubble sorting
<script>
function fn(arr) {
for (var i = 0; i <= arr.length - 1; i++) { //外层负责趟数
for (var j = 0; j <= arr.length - i - 1; j++) { //内层负责每次交换的次数
if (arr[j] > arr[j + 1]) {
var temp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = temp
}
}
}
return arr
}
console.log(fn([20, 80, 15, 2, 69, 35]));
</script>
Use function encapsulation to determine leap years and normal years
Declare a lock, if it is a leap year, return true, if it is not a leap year, return false
<script>
function isRunYear(year) {
var flag = false;
if (year % 4 == 0 && year % 400 != 0 || year % 400 == 0) {
flag = true;
}
return flag
}
console.log(isRunYear(2000))
console.log(isRunYear(2001))
</script>
Mutual calls between functions
Each code is a special code block, in order to complete a special task, functions can call each other
<script>
function fn1() {
console.log(111);
fn2()
}
fn1();
function fn2() {
console.log(222);
}
</script>
Case of mutual calling of functions
<script>
function fn1() {
console.log(111);
fn2();
console.log('fn1')
}
function fn2() {
console.log(222);
console.log('fn2')
}
fn1()
</script>
The number of days in February to call between functions
In the feBruary function, the isRunYear function is called in the if judgment statement and passed in. If it is true, there will be 29 days in February, and if it is false, there will be 28 days in February.
<script>
function feBruary() {
var year = prompt("请输入当前的年份")
if(isRunYear(year)) {
alert('当前是闰年 2月份有29天')
}else {
alert('当前是平年 2月份有28天')
}
}
feBruary() //调用函数
function isRunYear(year) {
var flag = false;
if(year % 4 ==0 && year % 400 != 0 || year % 400 == 0) {
flag = true;
}
return flag
}
</script>
Two ways to declare functions
function keyword declaration
<script>
function fn(str) {
console.log(str);
}
fn('hello')
</script>
Function expression declaration function
<script>
var fn = function(str) {
console.log(str)
}
fn('hello word')
</script>
note
- fn is a variable name, not a function name
- The way of declaring functions is similar to declaring variables, except that one stores the variable and the other stores the function
- Function expressions can also pass parameters.