当我们不确定有多少个参数传递的时候,可以用 arguments 来获取。在 JavaScript 中,arguments 实际上它是当前函数的一个内置对象。所有函数都内置了一个 arguments 对象,arguments 对象中存储了传递的所有实参。
arguments展示形式是一个伪数组,因此可以进行遍历。伪数组具有以下特点:
- 具有 length 属性
- 按索引方式储存数据
- 不具有数组的 push , pop 等方法
// arguments的使用 只有函数才有arguments对象,而且每个函数都内置好了这个arguments
function fn() {
console.log(arguments)
console.log(arguments.length)
console.log(arguments[1]);
}
fn(1, 2, 3);
fn(2, 5, 6, 7, 8, 9, 1, 2)
// 伪数组 并不是真正意义上的数组
// 1.具有数组length属性
// 2.按照索引的方式进行存储的
// 3.它没有真正数组的一些方法 pop(),push()等等
输入一个不定长度的数组,返回该数组的最大值:
循环遍历的方法:
function maxValue() {
var max = arguments[0];
for (var i = 0; i < arguments.length; i++) {
if (max < arguments[i]) {
max = arguments[i];
}
}
return max;
}
console.log(maxValue(2, 4, 5, 9));
console.log(maxValue(12, 4, 9));
reduce() 是数组的归并方法,会对数组每一项进行遍历,但是reduce() 可同时将前面数组项遍历产生的结果与当前遍历项进行运算。
语法:array.reduce(function(total, currentValue, currentIndex, arr), initialValue);是
total: 必需。初始值, 或者计算结束后的返回值。
currentValue: 必需。当前元素。
currentIndex: 可选。当前元素的索引;
arr: 可选。当前元素所属的数组对象。
initialValue: 可选。传递给函数的初始值,相当于total的初始值。
//在函数中使用
function sum(...numbers) {
return numbers.reduce((preValue, currentValue) => {
return preValue + currentValue
})
}
console.log(sum(1, 2, 3, 4)); //10
console.log(sum(4, 5, 5, 1)); //15
关于reduce()详细原文链接:https://blog.csdn.net/weixin_44326167/article/details/123680199