Zero-based JavaScript introductory tutorial (31) – function parameters

Click here to view: full tutorial, source code and accompanying video

1. Scenario

In the previous article, we have seen the true face of JS functions. Now let's consider a new scenario, or take driving as an example, before our driving function is as follows:

		// 定义函数
        function driveCar() {
    
    
            console.log("1.打开车门");
            console.log("2.系好安全带");
            console.log("3.启动车辆");
            console.log("4.踩油门,开始驾驶");
        }

Now we have to refine the matter of driving, because after starting the vehicle, you must first shift the gear before you can step on the accelerator to drive. The car is divided into automatic gear and manual gear, automatic gear we need to hang forward gear, manual gear we need to hang a gear.

The problem now is that our driveCar()function only knows to drive, but we don't know whether to drive automatic or manual.

Implemented in life, when we are doing one thing, sometimes we need to provide some additional information. For example, to drive, we need to know what kind of car to drive. For example online shopping, we need to know what to buy. Even for addition, we need to know which two numbers to add.

Therefore, the execution of the function sometimes requires some additional information, which is implemented in the JS language through function parameters.

2. Function parameters

Function driveCar(), parentheses are used to fill in the parameters. Let's take a car as an example:

		function driveCar(type) {
    
    
            console.log("1.打开车门");
            console.log("2.系好安全带");
            console.log("3.启动车辆");
            if (type == "自动档") {
    
    
                console.log("4.挂前进档");
            } else if (type == "手动档") {
    
    
                console.log("4.挂1档");
            }
            console.log("5.踩油门,开始驾驶");
        }

The type in parentheses represents the parameters required by the function, which is actually a variable. We use the value in the type variable to determine whether to open the automatic gear or the manual gear when driving.

Then when calling the function, we tell the function whether we want to open the automatic gear or the manual gear and it is OK.

		// 开自动档
        driveCar("自动档");
        // 开手动档
        driveCar("手动档");

3. Running results

The above code has run the driveCar function twice, the first parameter is "自动挡", the second parameter is "手动挡", so the result of the code is as follows:

insert image description here
It can be seen that with the information provided by the parameters, we can perform different actions.

4. Summary

Things need to be specific, functions need parameter information, and that's it.

Guess you like

Origin blog.csdn.net/woshisangsang/article/details/123630584