【问题标题】:Is it bad to pass more arguments than the function declares? [closed]传递比函数声明更多的参数是不是很糟糕? [关闭]
【发布时间】:2021-12-06 08:35:49
【问题描述】:

我有一个函数

function callback(obj){...}

是否可以传入比函数签名中声明的更多的对象? 例如这样称呼它:

callback(theObject, extraParam);

我在 Firefox 上试了一下,好像没有问题,但是这样做是不是很糟糕?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    JavaScript 允许这样做,您可以将任意数量的参数传递给函数。

    它们可以在 arguments 对象中访问,该对象是一个类似数组的对象,具有包含调用函数时使用的参数值的数字属性,length 属性告诉您有多少个参数也被用于调用,还有一个 callee 属性,它是对函数本身的引用,例如你可以这样写:

    function sum(/*arg1, arg2, ... , argN  */) { // no arguments defined
      var i, result = 0;
      for (i = 0; i < arguments.length; i++) {
        result += arguments[i];
      }
      return result;
    }
    sum(1, 2, 3, 4); // 10
    

    arguments 对象可能看起来像一个数组,但它是一个普通对象,继承自 Object.prototype,但如果您想在其上使用 Array 方法,您可以直接从 Array.prototype 调用它们,例如,获取 真实数组 的常见模式是使用 Array slice 方法:

    function test () {
      var args = Array.prototype.slice.call(arguments);
      return args.join(" ");
    }
    test("hello", "world"); // "hello world"
    

    此外,您可以使用函数对象的length 属性了解函数需要多少个参数

    function test (one, two, three) {
      // ...
    }
    test.length; // 3
    

    【讨论】:

    • 你能在函数中调用test.length来测试用户输入了多少参数吗?
    • 或者可以使用[].slice.call(arguments);
    【解决方案2】:

    是的,它是一种很好的做法,并且是一个强大的 JavaScript 功能

    【讨论】:

    • 我认为这是一个好的做法值得商榷。我不认为这是一种好的做法,从函数签名中看不出该函数是否打算采用额外的参数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-21
    • 2015-10-14
    相关资源
    最近更新 更多