写三个例子,说说arguments的用处:
1.用arguments实现对传参的判断,增强函数的容错功能。
1 function avg() { 2 var num = 0, 3 len = 0; 4 5 for(var i = 0; i<arguments.length; i++) { 6 if(typeof arguments[i] != "number") { 7 continue; 8 } 9 num += arguments[i]; 10 len++; 11 } 12 13 num /= len; 14 return num; 15 } 16 17 console.log(avg(1,2,3,'dsd')); 18 console.log(avg(1,2,3,'3'));
2.邮箱验证中arguments的用处
1 /** 2 * @descciprion 用于表单验证 3 * @returns {boolean} 4 */ 5 function isEmail() { 6 if(arguments.length > 1) { 7 throw new Error("only one parameter") 8 } 9 10 var reg = /^w+((-w+) | (.w+))*@[A-Za-z0-9]+((. | -)[A-Za-z0-9]+)*.[A-Za-z0-9]+$/; 11 if (reg.test(arguments[0])) { 12 return true; 13 } else { 14 return false; 15 } 16 }
3.arguments.callee的组合与应用
1 function f(x, y, z) { 2 var a = arguments.length; 3 var b = arguments.callee.length; 4 console.log(a); 5 console.log(b); 6 7 if( a != b ) { 8 throw new Error("传递的参数不匹配"); 9 } else { 10 return x + y + z; 11 } 12 } 13 14 console.log(f(3, 4, 5));