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);