JavaScript 函数综合指南
JavaScript 中的函数
以下是 JavaScript 函数的综合指南和示例:
1.什么是函数?
函数是用于执行特定任务的可重用代码块。它在被调用时执行。
句法:
function functionName(parameters) { // Code to execute }
例子:
function greet(name) { console.log(`Hello, ${name}!`); } greet("Alice"); // Output: Hello, Alice!
2. JavaScript 中的函数类型
A. 函数声明
使用“function”关键字声明的函数。
例子:
function add(a, b) { return a + b; } console.log(add(2, 3)); // Output: 5
B. 函数表达式
函数也可以存储在变量中。
例子:
const multiply = function (a, b) { return a * b; }; console.log(multiply(2, 3)); // Output: 6
C.箭头函数(ES6)
编写函数的简洁语法。
句法:
const functionName = (parameters) => { // Code to execute };
例子:
const subtract = (a, b) => a - b; console.log(subtract(5, 3)); // Output: 2
D.匿名函数
没有名称的函数,通常用作回调。
例子:
setTimeout(function () { console.log("This runs after 2 seconds"); }, 2000);
E.立即调用函数表达式(IIFE)
定义后立即运行的函数。
例子:
(function () { console.log("IIFE is executed immediately!"); })();
3. 参数和实参
例子:
function greet(name, age) { console.log(`Hi ${name}, you are ${age} years old.`); } greet("Bob", 25); // Output: Hi Bob, you are 25 years old.
4.默认参数
如果没有传递参数,则为参数提供默认值。
例子:
function sayHello(name = "Guest") { console.log(`Hello, ${name}!`); } sayHello(); // Output: Hello, Guest!
5. 剩余参数
用于将不确定数量的参数作为数组处理。
例子:
function sum(...numbers) { return numbers.reduce((total, num) => total + num, 0); } console.log(sum(1, 2, 3, 4)); // Output: 10
6. 退货声明
函数可以使用“return”语句返回一个值。
例子:
function square(num) { return num * num; } console.log(square(4)); // Output: 16
7.回调函数
将一个函数作为参数传递给另一个函数并稍后执行。
例子:
function processUserInput(callback) { const name = "Charlie"; callback(name); } processUserInput((name) => { console.log(`Hello, ${name}!`); }); // Output: Hello, Charlie!
8. 高阶函数
接受其他函数作为参数或返回函数的函数。
例子:
function applyOperation(a, b, operation) { return operation(a, b); } const add = (x, y) => x + y; const multiply = (x, y) => x * y; console.log(applyOperation(3, 4, add)); // Output: 7 console.log(applyOperation(3, 4, multiply)); // Output: 12
9. 闭包
闭包是一种函数,即使外部函数执行完毕后,它仍能记住其外部变量。
例子:
function outerFunction(outerVariable) { return function innerFunction(innerVariable) { console.log(`Outer: ${outerVariable}, Inner: ${innerVariable}`); }; } const myFunction = outerFunction("Outside"); myFunction("Inside"); // Output: Outer: Outside, Inner: Inside
10. 函数作用域
函数有自己的局部作用域。
例子:
function showMessage() { let message = "Hello, World!"; console.log(message); } showMessage(); // console.log(message); // Error: message is not defined
11.递归
调用自身的函数。
例子:
function factorial(n) { if (n === 1) return 1; return n * factorial(n - 1); } console.log(factorial(5)); // Output: 120
12.纯函数
纯函数对相同的输入产生相同的输出,并且没有副作用。
例子:
function add(a, b) { return a + b; } console.log(add(2, 3)); // Output: 5
**嗨,我是 Abhay Singh Kathayat!**
我是一名全栈开发人员,精通前端和后端技术。我使用多种编程语言和框架来构建高效、可扩展且用户友好的应用程序。
请随时通过我的商务电子邮件联系我:kaashshorts28@gmail.com。