Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js 函数参数

作者:此甥孓狠善良   发布日期:2026-07-06   浏览:75

// 示例代码:函数参数的基本用法

// 定义一个简单的函数,带有两个参数
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.

解释说明:

  1. 普通参数add 函数接收两个参数 ab,并在函数体内对它们进行操作。
  2. 默认参数greet 函数定义了一个默认参数 name,如果调用时没有传递参数,则使用默认值 "Guest"
  3. 剩余参数sum 函数使用了剩余参数 ...numbers,它可以接收任意数量的参数并将它们作为一个数组处理。
  4. 解构赋值introduce 函数使用了解构赋值来直接从对象中提取属性作为参数。

上一篇:js round函数

下一篇:js throw error

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js fill方法

js 数组连接

js json数组

js 数组复制

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站