es6--扩展运算符和rest运算符

当编写一个函数的时候,如果参数的个数不确定的时候,我们可以使用扩展运算符...(三个点)


function abc(...arg){
    console.log(arg[0],arg[1]);
}

扩展运算符还有一个特别的使用,当我们需要复制数组的时候,因为数组是引用类型,存储的是内存地址,
当我们操作复制过来的数组,会影响到前面的数组,如let arr1=[1,2,3];let arr2=arr1;arr2.push(4);console.log(arr1)

所以为了避免上述情况的发生,可以进行下面的操作
let arr3 =[...arr1];arr3.push(4);console.log(arr3,'-----',arr1)


rest运算符和扩展运算符其实感觉一样,也是三个点

function rest(first,...arg){
    console.log(arg.length)
}


猜你喜欢

转载自www.cnblogs.com/cyany/p/9247327.html
今日推荐