javascript函数代码样例
时间: 2024-08-13 14:08:04 浏览: 56
JavaScript函数是可重用的代码块,用于封装特定任务并接受输入(参数),然后执行相应操作并可能返回结果。以下是一些基本的JavaScript函数代码样例:
1. **普通函数**:
```javascript
function addNumbers(a, b) {
return a + b;
}
console.log(addNumbers(5, 10)); // 输出: 15
```
2. **箭头函数** (简洁形式):
```javascript
const add = (a, b) => a + b;
console.log(add(5, 7)); // 输出: 12
```
3. **带有默认参数值**:
```javascript
function greet(name = 'World') {
return `Hello, ${name}!`;
}
console.log(greet()); // 输出: Hello, World!
console.log(greet('Alice')); // 输出: Hello, Alice!
```
4. **可变参数(...rest)**:
```javascript
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4)); // 输出: 10
```
5. **函数作为参数传递** (高阶函数):
```javascript
function applyOperation(operation, a, b) {
return operation(a, b);
}
function multiply(a, b) {
return a * b;
}
console.log(applyOperation(multiply, 2, 3)); // 输出: 6
```
阅读全文