- // 了解一个函数需要多少个变量
- function add_nums(num1, num2){
- return num1 + num2;
- }
- add_nums.length
- // 2 is the amount of parameters expected by the function add_nums
- // 使用“arguments”对象来了解一个函数接收到了多少个参数
- function add_nums(){
- return arguments.length;
- }
- add_nums(23,11,32,56,89,89,89,44,6); //this return the number 9
- // 当你需要检查参数个数的有效性的时候,或者当你需要创建一个不确定参数个数的函数的时候,这个技巧是很有用的。
- function sum_three_nums( ){
- if(arguments.length!=3) throw new Error('received ' + arguments.length + ' parameters and should work with 3');
- }
- sum_three_nums(23,43); //Return the error message
- function sum_num(){
- var total = 0;
- for(var i=0;i<arguments .length;i++){
- total+=arguments[i];
- }
- return total;
- }
- sum_num(2,34,45,56,56);