扩展运算符和rest运算符,它们都是...(三个点)
,它们能够很好的为咱们解决参数和对象数组未知状况下的编程,让咱们的代码更健壮和简洁。javascript
扩展运算符
function fun(...args){ console.log(args[0]); console.log(args[1]); console.log(args[2]); console.log(args[3]); } fun(1,2,3); // 1 // 2 // 3 // undefined
扩展运算符的一个用处java
let arr1=['www','jspang','com']; let arr2=arr1; // 因为数组对象其实是一个引用类型,所以arr2 与 arr1指向了同一处 console.log(arr2); arr2.push('shengHongYu'); //修改了 arr2 那么 arr1也会被修改 console.log(arr1); // 为了解决这个问题 let arr1 = ['11', '222', '2222']; let arr2 = [...arr1]; console.log(arr2); arr2.push('shengHongYu'); console.log(arr2); console.log(arr1);
const [o1, ...ops] = ['one', 'two', 'three']; // o1 one // ops ['two', 'three']
const ops = ['one', 'two', 'three']; const a = ['222',...ops]; console.log(a); // ["222", "one", "two", "three"]
reset运算符
若是你已经很好的掌握了对象扩展运算符,那么理解rest运算符并不困难,它们有不少类似之处,甚至不少时候你不用特地去区分。编程
function fun(first, ...arg) { console.log(arg.length); // 7 } fun(0, 1, 2, 3, 4, 5, 6, 7);
输出arg内容数组
function jspang(first,...arg){ for(let val of arg){ console.log(val); } } jspang(0,1,2,3,4,5,6,7);