// 示例代码:函数参数的基本用法
// 定义一个简单的函数,带有两个参数
function add(a, b) {
// 参数 a 和 b 是函数的输入
return a + b;
}
// 调用函数并传入参数
console.log(add(3, 5)); // 输出: 8
// 使用默认参数
function greet(name = "Guest") {
// 如果没有传入 name 参数,则使用默认值 "Guest"
console.log("Hello, " + name);
}
greet("Alice"); // 输出: Hello, Alice
greet(); // 输出: Hello, Guest
// 使用剩余参数(rest parameters)
function sum(...numbers) {
// numbers 是一个数组,包含所有传入的参数
return numbers.reduce((acc, curr) => acc + curr, 0);
}
console.log(sum(1, 2, 3, 4)); // 输出: 10
// 使用解构赋值作为函数参数
function introduce({ name, age }) {
console.log(`My name is ${name} and I am ${age} years old.`);
}
introduce({ name: "Bob", age: 30 }); // 输出: My name is Bob and I am 30 years old.
add 函数接收两个参数 a 和 b,并在函数体内对它们进行操作。greet 函数定义了一个默认参数 name,如果调用时没有传递参数,则使用默认值 "Guest"。sum 函数使用了剩余参数 ...numbers,它可以接收任意数量的参数并将它们作为一个数组处理。introduce 函数使用了解构赋值来直接从对象中提取属性作为参数。上一篇:js round函数
下一篇:js throw error
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站