我有一个典型的javascript函数与一些参数
my_function = function(content, options) { action }
Run Code Online (Sandbox Code Playgroud)
如果我这样调用函数:
my_function (options)
Run Code Online (Sandbox Code Playgroud)
参数"options"作为"内容"传递
我如何解决这个问题,所以我既可以通过两个论点,也可以只通过一个?谢谢
Fel*_*ing 95
您必须决定要将哪个参数视为单个参数.你不能把它当作两者兼顾,content而且options.
我看到两种可能性:
function(options, content)检查是否options定义:
function(content, options) {
if(typeof options === "undefined") {
options = content;
content = null;
}
//action
}
Run Code Online (Sandbox Code Playgroud)
但是你必须正确记录,如果你只将一个参数传递给函数会发生什么,因为通过查看签名不能立即清楚.
Dar*_*rov 25
my_function = function(hash) { /* use hash.options and hash.content */ };
Run Code Online (Sandbox Code Playgroud)
然后打电话:
my_function ({ options: options });
my_function ({ options: options, content: content });
Run Code Online (Sandbox Code Playgroud)
Sar*_*raz 18
像这样:
my_function (null, options) // for options only
my_function (content) // for content only
my_function (content, options) // for both
Run Code Online (Sandbox Code Playgroud)
ulo*_*lou 12
使用ES6:
function test(a, b = 3) {
console.log(a, ' ', b);
}
test(1); // Output: 1 3
test(1, 2); // Output: 1 2
Run Code Online (Sandbox Code Playgroud)
或者,您也可以根据获得的内容类型来区分。选项曾经是对象,内容曾经是字符串,所以您可以这样说:
if ( typeof content === "object" ) {
options = content;
content = null;
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您对重命名感到困惑,则可以使用arguments数组,该数组可以更简单:
if ( arguments.length === 1 ) {
options = arguments[0];
content = null;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
98422 次 |
| 最近记录: |