JavaScript-the concept and application of functions (1)

Concept of function

    In JavaScript, a lot of the same code or code with similar functions may be defined. These codes may need to be reused a lot. Although the for loop statement can achieve some simple repetitive operations, it is more limited. At this time, we can Use js中的函数.
函数: It encapsulates a code block that can be repeatedly called and executed, and a large amount of code can be reused through this code block. E.g:

//1.求1-100的累加和
var sum = 0
for (var i=1;i<=100;i++){
    
    
	sum+=i;
}
console.log(sum)

//2.求10-50的累加和
var sum = 0
for (var i=1;i<=50;i++){
    
    
	sum+=i;
}
console.log(sum)

//以上是两个累加和的方法,需要分别设置条件和定义变量
//下面这种方法是采用函数封装的方法来求两个的累加和

//3.函数的方法
function getSum(num1,num2){
    
    
	for (var i=num1;i<=num2;i++){
    
    
	sum+=i;
}
console.log(sum)
}
getSum(1,100)
getSum(10,50)
//这样值就求出来了,如果需要求其他范围的值,在下面getSum里面定义就可以了

Insert picture description here
The use of a function is divided into two steps: declaring the function and calling the function
1. 声明函数
function(){ function body } function say(){ console.log('hellword') } Note: (1), function The keywords of the function declaration are all lowercase (2) A function is to do something, the function name is generally a verb (3), the function does not call itself and does not execute








2. Call the function 声明函数本身并不会执行代码,只有调用时才会执行函数体代码
function name ();
say ();调用函数的时候千万不要忘记添加小括号

3. Encapsulation of functions

  • The encapsulation of functions is to pass one or more functions 函数的方式封装起来, and only provide a simple function interface to the outside.
  • Simple understanding: packaging is similar to integrating computer accessories into the chassis (similar to express packaging)

After seeing so much, let's make a case!

Case: Use functions to calculate the cumulative sum between 1-500Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_45054614/article/details/107592507