传递比函数声明更多的参数是不是很糟糕? [英] Is it bad to pass more arguments than the function declares?

查看:128
本文介绍了传递比函数声明更多的参数是不是很糟糕?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数

function callback(obj){...}

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

Is it okay to pass in more objects than were declared in the function signature? e.g. call it like this:

callback(theObject, extraParam);

我在Firefox上尝试过它并没有出现问题,但是它不好要做到这一点?

I tried it out on Firefox and it didn't seem to have a problem, but is it bad to do this?

推荐答案

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

JavaScript allows this, you can pass any arbitrary number of arguments to a function.

可以在 <$ c $中访问它们。 c> arguments object,它是一个类数组的对象,其数字属性包含调用函数时使用的参数值, length 属性,它告诉你调用也使用了多少个参数,以及被调用者属性,它是对函数本身的引用,例如你可写:

They are accessible in the arguments object which is an array-like object that has numeric properties containing the values of the arguments that were used when the function was invoked, a length property that tells you how many arguments have been used on the invocation also, and a callee property which is a reference to the function itself, for example you could write:

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

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

The arguments object may look like an array, but it is a plain object, that inherits from Object.prototype, but if you want to use Array methods on it, you can invoke them directly from the Array.prototype, for example, a common pattern to get a real array is to use the Array slice method:

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

此外,您可以知道函数期望的参数数量,使用函数对象的 length 属性:

Also, you can know how many arguments a function expects, using the length property of the function object:

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

这篇关于传递比函数声明更多的参数是不是很糟糕?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆