


Let's talk about the definition and basic use of JavaScript functions
This article brings you relevant knowledge about javascript, which mainly organizes issues related to the definition and basic use of functions, including definitions with function statements, function calls, and undefined Let’s take a look at the actual parameters and so on. I hope it will be helpful to everyone.
[Related recommendations: javascript video tutorial, web front-end】
1. Define with function statements
Let’s give an example first. The function of this function is to return the sum of array elements;
function sumArray(arr) { var sum = 0; for(var i = 0,aLength = arr.length;i < aLength;i++) { sum += arr[i]; } return sum; }
Keyword function
There is a space after it, sumArray
is the name of the function, and its naming convention is the same as that of variable names: can only contain letters, numbers, underscores, and dollar signs, and cannot start with a number or be a keyword.
The parameters in brackets are also called formal parameters. Only the parameter name is required. Parameters can be 0
, 1
or more, separated by ,
, {}
is included in the middle Function body. Contains one or more statements. The function body is used to implement the function of the function.
Keywordreturn
is followed by the return value of the function. The function can also have no return value. After the function is finished running, return
this sentence will exit the operation, return
The following statement will no longer run. The return value is the output of the function.
For a function defined in this way, the function can be called both before and after the function definition, as long as the function and the statement calling the function are in the same source file.
2. Use expression definition
Define a function in the form of an expression, which is to use an assignment expression to assign the function to a variable . This is actually to see the function as into a variable. At this time, the function can have a name or no name. The function without a name is called anonymous function.
- With name;
var funct = function getMax(a,b) { return a>b?a:b; };//注意这后面的分号不能少,因为我们定义的是一个变量!
and are defined with function statementsThe difference is that they can only be defined after the function definition statementCall this function, and when calling, you can only use the variable name funct
, but not the function name getMax
, such as:
var funct = function getMax(a,b) { return a>b?a:b; }; console.log(funct(1,2));//输出2
- Anonymous function;
The so-called anonymous function is the keywordfunction
followed directly by the parameter list:
var funct = function(a,b) { return a>b?a:b; };
This function has no name, it is assigned to the variablefunct
, so it is called an anonymous function. Similarly, can only call this function after this statement.
var funct = function(a,b) { return a>b?a:b; }; console.log(funct(1,2));//输出2
Summary: Defining a function with an expression is ready for use. Once defined, the function can only be called after this statement
3 .Function calling
In the fourth training, we once introduced that objects can have their own methods, and of course these are also functions. The call of this function is slightly different from the functions defined in the previous two levels.
//函数的定义:求三个数的最大值 function max(a,b,c) { if(a > b) { if(a > c) return a; else return c; } else { if(b > c) return b; else return c; } } //调用该函数 var result = max(1,2,3);//result为3 console.log(result);//输出3
When calling a function, you need to pass in the same number of specific values as the formal parameters. The above function has 3
parameters, so when calling the following, pass in 3
specific values, 1
is passed to parameter a
, 2
is passed to parameter b
, 3
Pass parameter c
. The return value of the function is passed to the variable result
through the assignment symbol =
. If there is no return
keyword in the function body, undefined
will be returned.
Call the function defined in the object:
var ob = { id:1, getMax:function(a,b) { return a>b?a:b; } }; var result = ob.getMax(2,1);//result值为2 var result1 = ob["getMax"](2,1);//result1的值也是2
The difference from the above is that to locate the function here, you need to use the object name. Function name
or Object name ["function name"]
, the others are the same.
4. Undefined actual parameters
In most programming languages, the number and type of actual parameters passed in when calling a function will be checked, and JavaScript
Both does not check the type of actual parameters, nor does it check the number of actual parameters. The actual parameters in JavaScript
will match the formal parameters in order from left to right, for example:
function myFunction(a,b,c) { console.log(a); console.log(b); console.log(c); } myFunction(1,2,3);
actual parameters1
Incoming formal parameters a
, actual parameters 2
Incoming formal parameters b
, Incoming actual parameters 3
Incoming formal parameters c
. When the number of actual parameters is less than the formal parameters, the value undefined
will be passed to the right formal parameter. For example:
function myFunction(a,b,c) { console.log(a); console.log(b); console.log(c); } myFunction(1,2);
actual parameter1
pass in formal parametera
,actual parameter2
pass in formal parameterb
,undefined
Incoming formal parametersc
. If you only want to pass data to the parameters on the right, you can pass undefined
to the first few actual parameters. For example:
function myFunction(a,b,c){ console.log(a); console.log(b); console.log(c); } myFunction(undefined,1,2);
The above two methods are not rigorous enough. The best practice is to set a default value
for formal parameters that may be passed in an undefined value. like:
function getSum(a,b,c) { if(c === undefined) c = 0; console.log(a+b+c); } myFunction(1,2);
5.实参对象
JavaScript
一切都是对象,实参也是一个对象,有一个专门的名字arguments
,这个对象可以看成一个数组(类数组,不是真的数组),实参从左到右分别是arguments[0]、arguments[1]...
,arguments.length
表示实参的个数。
//求参数的和 function getSum() { var aLength = arguments.length; var sum = 0; for(var i = 0;i < aLength;i++) { sum += arguments[i]; } return sum; } console.log(getSum(1,2,3,4,5))//输出15
这里的形参直接省略,使用arguments[i]
表示。
6.对象作为参数
复杂的函数通常多达十几个参数,尽管JavaScript
不做参数个数和类型的检查,但是调用时实参的顺序不能乱。开发人员需要检查每一个实参和形参的对应关系,这样效率很低。一种很好的解决方案是使用对象作为参数,函数会根据对象的属性名操作参数。
function myFunction(obj) { console.log(obj.name); obj.number++; return obj.number; } myObj = {name:"myObj",number:34}; myFunction(myObj);//输出myObj console.log(myObj.number);//输出35
7.函数对象作为另一个函数的参数
一个函数(为方便行文,称为a
函数)可以作为另外一个函数(称为b
函数)的参数,b
函数最终可以返回一个具体的值。
从原理上来说,b
函数在自己的函数体内调用了a
函数,所以需要把a
函数的名字作为实际参数传递给b
函数。如下:
//求最大值 function getMax(a,b) { return a>b?a:b; } //求最小值 function getMin(a,b) { return a<b?a:b; } //下面这个函数以函数作为参数,并最终返回一个值 function getM(func,num1,num2) { return func(num1,num2); } getM(getMax,1,2);//返回2 getM(getMin,1,2);//返回1
我们把a
函数的名字(getMax
或者getMin
)传给b
函数(getM()
),然后在b
函数内部调用传入的a
函数,得到相关的结果。
【相关推荐:javascript视频教程、web前端】
The above is the detailed content of Let's talk about the definition and basic use of JavaScript functions. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
