js操作函数,判断传递参数合法性和个数

来源:互联网 发布:金红米i7手机数据参数 编辑:程序博客网 时间:2024/06/06 02:20

  1. // 了解一个函数需要多少个变量   
  2. function add_nums(num1, num2){   
  3. return num1 + num2;   
  4. }   
  5. add_nums.length   
  6. // 2 is the amount of parameters expected by the function add_nums   

  1. // 使用“arguments”对象来了解一个函数接收到了多少个参数   
  2. function add_nums(){   
  3. return arguments.length;   
  4. }   
  5. add_nums(23,11,32,56,89,89,89,44,6); //this return the number 9   

  1. // 当你需要检查参数个数的有效性的时候,或者当你需要创建一个不确定参数个数的函数的时候,这个技巧是很有用的。  
  2. function sum_three_nums( ){   
  3. if(arguments.length!=3) throw new Error('received ' + arguments.length + ' parameters and should work with 3');   
  4. }   
  5. sum_three_nums(23,43); //Return the error message   
  6. function sum_num(){   
  7. var total = 0;   
  8. for(var i=0;i<arguments .length;i++){   
  9. total+=arguments[i];   
  10. }   
  11. return total;   
  12. }   
  13. sum_num(2,34,45,56,56);   
0 0
原创粉丝点击