你如何生成一个警告没有足够的参数的函数?

时间:2017-12-09 09:46:25

标签: javascript function arguments anonymous

如果您使用不同数量的必需参数动态生成函数,那么如何确定 如果 将来的数< / strong>提供参数到函数调用 就足够了 和/或如何确保您的函数警告 /关于必需或缺少 参数数量

匿名函数的结构体可以简单如下:

fucntion( x, y, z ) {
        /*test for the arguments supplied*/
    if( notEnoughArguments )
        /*exit the function and return a warning*/   
        /*otherwise, say ...*/
     return x*y*x
    }

问题:您事先不知道某个函数需要多少个参数,并且您不确定在函数调用时可用/提供了多少个参数。

2 个答案:

答案 0 :(得分:0)

您可以在函数内使用arguments对象。对于例如arguments.length将提供传递给函数的参数数量。查看https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments了解详情

答案 1 :(得分:0)

您可以查看arguments长度与Function.length

在功能......

  

length属性指定了期望的参数数量   功能

arguments对象是一个类似于object的数组,它包含传递给函数的所有参数。

function multi(x, y, z) {
  if(arguments.length < multi.length) {
    console.log('not enough arugments');
    return null;
  }

  return x * y * x
}

multi();

console.log(multi(1, 2, 3));