如何在node.js中查找进入构造函数的参数数量

How to find number of arguments that come into a constructor in node.js

本文关键字:构造函数 参数 数数 查找 node js      更新时间:2023-09-26

我在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变量。

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

每个函数中都有一个自变量变量。

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

有一个局部变量自变量,它包含传递给函数的所有值。

arguments.length 

这将给出计数。