【问题标题】:How to find number of arguments that come into a constructor in node.js如何在 node.js 中查找进入构造函数的参数数量
【发布时间】:2016-04-19 10:27:53
【问题描述】:

我在 node.js 中有一个构造函数,如下所示。

function Tree() {
  //Redirect to other functions depends upon argument count.
}

我创建了类似的对象

var theTree = new Tree('Redwood');
var theTree = new Tree('Redwood',5);
var theTree = new Tree('Redwood',10,"USA");

我的要求是我想根据传入构造函数的参数数量重定向到不同的函数。如何找到参数的数量?

【问题讨论】:

  • arguments.length inside function Tree() 应该可以解决问题。

标签: javascript angularjs node.js object constructor


【解决方案1】:

您只需使用arguments.length 变量。

有关更多信息,您可以阅读有关 arguments 对象的信息:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/arguments

【讨论】:

    【解决方案2】:

    每个函数都有一个参数变量。

    function Tree() {
      console.log(arguments)
    }
    

    【讨论】:

      【解决方案3】:

      有一个局部变量arguments,其中包含传递给函数的所有值。

      arguments.length 
      

      这将给出计数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-09
        • 2018-03-27
        • 1970-01-01
        • 2016-01-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多