函数参数

一、对位传参

function fn1(name,sex,age){
	console.log("用户的姓名为 ",name,",性别为 ",sex,",年龄为 ",age);
}
fn1("tjh","男",18);

--》用户的姓名为  tjh ,性别为  男 ,年龄为  18

二、对像传参

function fn1(porent){
	console.log("用户的姓名为 ",porent.name,",性别为 ",porent.sex,",年龄为 ",porent.age);
}
fn1({name: "tjh",sex: "男",age: 18});

--》用户的姓名为  tjh ,性别为  男 ,年龄为  18

三、参数默认值(三种方式)

//ES6的写法
function fn1(porent = {name: "lj"}){
	console.log("用户的姓名为 ",porent.name,",性别为 ",porent.sex,",年龄为 ",porent.age);
}
fn1({name: "tjh"});

--》用户的姓名为  tjh ,性别为  undefined ,年龄为  undefined
//ES5的方法
function fn1(porent){
	porent.name = (porent.name == undefined ? "tjh":porent.name),
	porent.sex = (porent.sex == undefined ? "女":porent.sex)
	console.log("用户的姓名为 ",porent.name,",性别为 ",porent.sex,",年龄为 ",porent.age);
}
fn1({name: "tjh",age: 20});

--》用户的姓名为  tjh ,性别为  女 ,年龄为  20
//ES5的方法
function fn1(porent){
	porent.name = (porent.name || "wzh"),
	porent.sex = (porent.sex || "中")
	console.log("用户的姓名为 ",porent.name,",性别为 ",porent.sex,",年龄为 ",porent.age);
}
fn1({name: "t",age: 20});

--》用户的姓名为  t ,性别为  中 ,年龄为  20

//此方法有缺陷,当传入的值为0的时候,会传入默认值

四、Arguments(将参数以伪数组的形式传入进行操作,有下标)

function f1(n1,n2,n3,n4,n5){
	let arr = Array.prototype.slice.call(arguments);  //将伪数组转化为真数组,用call方法修改this指向,调用数组的方法
        return arr.reduce(function(ele1,ele2){
		return ele1 + ele2;
	})
}
f1(1,2,3,4,5);

--》15
function f1(n1,n2,n3,n4,n5){
	let arr = Array.from(arguments);
	return arr.reduce(function(ele1,ele2){
		return ele1 + ele2;
	})
}
f1(1,2,3,4,5);

--》15

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
函数参数是在定义函数时用于接收传递给函数的值或变量的占位符。在Python中,函数参数有以下几种类型: 1. 位置参数(Positional Arguments):按照定义函数时的顺序,依次传递给函数的参数。调用函数时,传递的参数值与函数定义时的参数一一对应。 2. 默认参数(Default Arguments):在定义函数时,为参数提供默认值。调用函数时,如果不传递该参数的值,则使用默认值。 3. 关键字参数(Keyword Arguments):调用函数时,通过参数名来指定传递的参数值,不需要按照定义函数时的顺序传递。 4. 可变长度参数(Variable-Length Arguments):可以接受任意数量的参数。在函数定义时使用星号 (*) 来表示,有两种形式: - *args:接受任意数量的位置参数,以元组(tuple)的形式传递给函数。 - **kwargs:接受任意数量的关键字参数,以字典(dictionary)的形式传递给函数。 下面是一个示例,展示了不同类型的函数参数: ```python def greet(name, message="Hello"): print(f"{message}, {name}!") def calculate_sum(*args): total = sum(args) print(f"The sum is: {total}") def print_info(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") # 调用函数 greet("Alice") # 使用默认值 greet("Bob", "Hi") # 提供自定义值 calculate_sum(1, 2, 3, 4, 5) print_info(name="Alice", age=25, city="New York") ``` 输出结果为: ``` Hello, Alice! Hi, Bob! The sum is: 15 name: Alice age: 25 city: New York ``` 这是函数参数的基本概念和用法,希望能对你有所帮助!如果还有其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值