arguments
- arguments存放的是传递过来的实参
- arguments展示形式是一个伪数组,可以进行遍历
- 伪数组具有length属性,按索引方式存储数据,不具有数组的push、pop等方法
function getSum(){
// console.log(arguments);
let sum = 0
for(let i = 0;i<arguments.length;i++){
s += arguments[i]
}
}
getSum(2,3,4)
arguments的使用:返回所有调用参数相加后的结果
- 问题描述
函数 useArguments 可以接收 1 个及以上的参数。请实现函数 useArguments,返回所有调用参数相加后的结果。本题的测试参数全部为 Number 类型,不需考虑参数转换。
- 解题
1、for循环
function useArguments() {
let sum = 0;
for(let i = 0; i < arguments.length; i++){
sum += arguments[i];
}
return sum;
}
2、由于arguments只是类数组,并没有数组的一些方法,所以可以将arguments转换成数组进行累加
function useArguments() {
let arr = [...arguments];
return arr.reduce((total, num)=> total += num)
}
rest参数
- 将参数以数组的形式存放
- 剩余参数只能写在最后,其他参数不可以写在剩余参数后面
function sum(a,b,...other){
console.log(other);
}
sum(1,3,5,6)
// 剩余参数的写法...args(名称随意)
const sum=(a,b,...args)=>{
// 使用的时候只用args
console.log(a,b,args)
};
sum(1,2,1,4);//1 2 Array(2)
剩余参数的使用
可以使用剩余参数代替arguments(arguments在箭头函数的中无法使用)
const fun=function(){
console.log(arguments);
}
fun(1,2,3);//Arguments(3),类数组
// 使用剩余参数在箭头函数中使用
const fun1=(...args)=>{
console.log(args);
}
fun1(1,2,3,4);//(4) [1, 2, 3, 4]
与对象和数组的解构赋值一起使用
// 与数组解构赋值
const [a,...args]= [11,22,33];
console.log(a,args); // 11 Array(2)
// 与对象解构赋值
const {age,...args1}={age:12,name:"xiaoming",sex:"nan"};
// args1是剩余元素
console.log(age,args1);// 12 object
拓展运算符…
- 将一个数组转为用逗号分隔的参数序列
- 数组展开,不改变原数组
- 通过扩展运算符实现的是浅拷贝,修改了引用指向的值,会同步反映到新数组
- 定义了遍历器(Iterator)接口的对象,都可以用扩展运算符转为真正的数组,如果对没有 Iterator 接口的对象,使用扩展运算符,将会报错
求数组最值、数组合并
const arr = [1,2,3]
console.log(...arr);
// 典型运用场景:求数组最值、合并数组
console.log(Math.max(...arr));
const arr1 = [2,3,4]
//数组的合并
const arr2 = [...arr, ...arr1]
console.log(arr2);
数组复制
// 复制数组,原数组改变不影响被复制的数组
const a=[11,2,2,3]
const b=a;
const c= [...a];
a[0]=18;
console.log(b); // [18,2,2,3]
console.log(c);// [11,2,2,3]
将类数组转化为数组
// 箭头函数是使用不了arguments
// const fun=()=>console.log(arguements);
const fun=function(){
a=([...arguments]);
a.push(22);
console.log(a);//(4) [11, 22, 33, 22]
}
fun(11,22,33);
展开字符串
console.log(..."hello") // h e l l o
对象展开、对象合并
const people={
name:"xiaoming",
age:12
}
const people1={...people}
console.log(people1===people);//fales
const apple={
clor:"green",
shape:"big"
}
const apple1={
clor:"red",
shape:"big",
height:12
}
console.log({...apple,...apple1}); //{clor: "red",height: 12,shape: "big"}
复制对象
const people={
name:"xiaoming",
age:12,
}
const people1=people;
const people2={...people};
people.age=14;
console.log(people1); //{age:14,name:"xiaoming"}
console.log(people2); //{age:12,name:"xiaoming"}