动态参数——arguments

本文探讨了JavaScript中如何处理参数不固定的情况,如使用arguments对象来接收并操作动态参数,以及在参数固定时如何选择使用形参。通过实例演示了求最大值函数的两种实现方式:一是利用arguments适应不确定数量的参数,二是直接使用固定形参。
摘要由CSDN通过智能技术生成

1.遇到参数不固定的情况:arguments

arguments:函数内部的特殊对象,用于接受所有参数,得到的是伪数组。

function fn () {
			console.log( arguments );// arguments = [1, 2, 3, 'a', 'aa']
			for ( let i = 0; i < arguments.length; i++ ) {
				console.log( arguments[i] );
			}
		}
		fn( 1, 2, 3, 'a', 'aa');

2.如果参数不固定用arguments, 但是如果参数固定的话, 直接用形参

// 求若干个数的最大值

function getMax() {
            // console.log( arguments ); arguments = [123, 3, 6, 9, 12, 1234, 666, 9]
            // 假设值最大值
            let max = arguments[0];
            // 找到每个实参
            for (let i = 0; i < arguments.length; i++) {

                if (max < arguments[i]) max = arguments[i];

            }
            // 打印
            console.log(max);
        }

        getMax(123, 3, 6, 9, 12, 1234, 666, 9);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值