javascript:函数中可选的第一个参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3147640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript: optional first argument in function
提问by salmane
I have a typical javascript function with some parameters
我有一个带有一些参数的典型 javascript 函数
my_function = function(content, options) { action }
if I call the function as such :
如果我这样调用函数:
my_function (options)
the argument "options" is passed as "content"
参数“选项”作为“内容”传递
how do i go around this so I can either have both arguments passed or just one ? thank you
我该如何解决这个问题,以便我可以同时传递两个参数或仅传递一个参数?谢谢你
回答by Felix Kling
You have to decide as which parameter you want to treat a single argument. You cannot treat it as both, contentand options.
您必须决定要将单个参数视为哪个参数。你不能把它当作两者,content和options。
I see two possibilities:
我看到两种可能性:
- Either change the order of your arguments, i.e.
function(options, content) Check whether
optionsis defined:function(content, options) { if(typeof options === "undefined") { options = content; content = null; } //action }But then you have to document properly, what happens if you only pass one argument to the function, as this is not immediately clear by looking at the signature.
- 要么改变你的论点的顺序,即
function(options, content) 检查是否
options定义:function(content, options) { if(typeof options === "undefined") { options = content; content = null; } //action }但是,您必须正确记录,如果您只向函数传递一个参数会发生什么,因为通过查看签名并不能立即清楚这一点。
回答by Darin Dimitrov
my_function = function(hash) { /* use hash.options and hash.content */ };
and then call:
然后调用:
my_function ({ options: options });
my_function ({ options: options, content: content });
回答by Sarfraz
Like this:
像这样:
my_function (null, options) // for options only
my_function (content) // for content only
my_function (content, options) // for both
回答by ulou
With ES6:
使用 ES6:
function test(a, b = 3) {
console.log(a, ' ', b);
}
test(1); // Output: 1 3
test(1, 2); // Output: 1 2
回答by gblazex
Or you also can differentiate by what type of content you got. Options used to be an object the content is used to be a string, so you could say:
或者,您也可以根据获得的内容类型进行区分。选项曾经是一个对象,内容曾经是一个字符串,所以你可以说:
if ( typeof content === "object" ) {
options = content;
content = null;
}
Or if you are confused with renaming, you can use the arguments array which can be more straightforward:
或者,如果您对重命名感到困惑,您可以使用更直接的参数数组:
if ( arguments.length === 1 ) {
options = arguments[0];
content = null;
}
回答by Wilt
There is a nice read on Default parameters in ES6 on the MDN website here.
In ES6 you can now do the following:
在此处的 MDN 网站上对ES6中的默认参数有很好的阅读。
在 ES6 中,您现在可以执行以下操作:
secondDefaultValue = 'indirectSecondDefaultValue';
function MyObject( param1 = 'firstDefaultValue', param2 = secondDefaultValue ){
this.first = param1;
this.second = param2;
}
You can use this also as follows:
您也可以按如下方式使用它:
var object = new MyObject( undefined, options );
Which will set default value 'firstDefaultValue'for first param1and your optionsfor second param2.
这将为'firstDefaultValue'firstparam1和您options的 second设置默认值param2。
回答by DynamicDan
There are 2 ways to do this.
有两种方法可以做到这一点。
1)
1)
function something(options) {
var timeToLive = options.timeToLive || 200; // default to 200 if not set
...
}
2)
2)
function something(timeToDie /*, timeToLive*/) {
var timeToLive = arguments[1] || 200; // default to 200 if not set
..
}
In 1), optionsis a JS object with what ever attributes are required. This is easier to maintain and extend.
在 1) 中,options是一个具有所需属性的 JS 对象。这更易于维护和扩展。
In 2), the function signature is clear to read and understand that a second argument can be provided. I've seen this style used in Mozilla code and documentation.
在 2) 中,函数签名清晰易读,可以提供第二个参数。我在 Mozilla 代码和文档中看到过这种风格。
回答by ovatto
I've created a simple library for handling optional arguments with JavaScript functions, see https://github.com/ovatto/argShim. The library is developed with Node.js in mind but should be easily ported to work with e.g. browsers.
我创建了一个简单的库,用于使用 JavaScript 函数处理可选参数,请参阅https://github.com/ovatto/argShim。该库是用 Node.js 开发的,但应该很容易移植到浏览器等。
Example:
例子:
var argShim = require('argShim');
var defaultOptions = {
myOption: 123
};
var my_function = argShim([
{optional:'String'},
{optional:'Object',default:defaultOptions}
], function(content, options) {
console.log("content:", content, "options:", options);
});
my_function();
my_function('str');
my_function({myOption:42});
my_function('str', {myOption:42});
Output:
输出:
content: undefined options: { myOption: 123 }
content: str options: { myOption: 123 }
content: undefined options: { myOption: 42 }
content: str options: { myOption: 42 }
The main target for the library are module interfaces where you need to be able to handle different invocations of exported module functions.
该库的主要目标是模块接口,您需要能够处理导出模块函数的不同调用。
回答by ant
Just to kick a long-dead horse, because I've had to implement an optional argument in the middle of two or more required arguments. Use the argumentsarray and use the lastone as the required non-optional argument.
只是为了踢一匹死马,因为我不得不在两个或更多必需参数的中间实现一个可选参数。使用arguments数组并使用最后一个作为必需的非可选参数。
my_function() {
var options = arguments[argument.length - 1];
var content = arguments.length > 1 ? arguments[0] : null;
}
回答by skinneejoe
You can pass all your optional arguments in an object as the first argument. The second argument is your callback. Now you can accept as many arguments as you want in your first argument object, and make it optional like so:
您可以将对象中的所有可选参数作为第一个参数传递。第二个参数是你的回调。现在,您可以在第一个参数对象中接受任意数量的参数,并将其设为可选,如下所示:
function my_func(op, cb) {
var options = (typeof arguments[0] !== "function")? arguments[0] : {},
callback = (typeof arguments[0] !== "function")? arguments[1] : arguments[0];
console.log(options);
console.log(callback);
}
If you call it without passing the options argument, it will default to an empty object:
如果您在不传递 options 参数的情况下调用它,它将默认为一个空对象:
my_func(function () {});
=> options: {}
=> callback: function() {}
If you call it with the options argument you get all your params:
如果您使用 options 参数调用它,您将获得所有参数:
my_func({param1: 'param1', param2: 'param2'}, function () {});
=> options: {param1: "param1", param2: "param2"}
=> callback: function() {}
This could obviously be tweaked to work with more arguments than two, but it get's more confusing. If you can just use an object as your first argument then you can pass an unlimited amount of arguments using that object. If you absolutely need more optional arguments (e.g. my_func(arg1, arg2, arg3, ..., arg10, fn)), then I would suggest using a library like ArgueJS. I have not personally used it, but it looks promising.
这显然可以调整为使用比两个更多的参数,但它会变得更加混乱。如果您可以只使用一个对象作为您的第一个参数,那么您可以使用该对象传递无限数量的参数。如果您绝对需要更多可选参数(例如 my_func(arg1, arg2, arg3, ..., arg10, fn)),那么我建议使用像ArgueJS这样的库。我没有亲自使用它,但它看起来很有希望。

