如何让函数接受--命名参数(foo({a: 'hello', b: 'it is me'})) 或位置参数(foo('hello', 'it is me'))?
我理解,可以通过向函数传递一个对象来模拟命名参数:
function foo(options) {
options = options || {};
var a = options.a || 'peanut'; // whatever default value
var b = options.b || 'butter'; // whatever default value
console.log(a, b);
}
// ES6 allows automatic destructuring
function foo({a = 'peanut', b = 'butter'} = {}) {
console.log(a, b);
}但这不允许我接受将要通过的位置论点。
我想使用ES6,但是来自ES5的任何东西都可以。
发布于 2015-12-17 13:53:43
首先,我真的建议坚持一种方法。就像你说的,使用“命名”
function foo({a = 'peanut', b = 'butter'} = {}) {
console.log(a, b);
}或位置论点:
function foo(a = 'peanut', b = 'butter') {
console.log(a, b);
}选择一个更适合您的功能,不混合两个。
如果您确实出于某种原因需要这两种方法,那么您可以使用standard overloading techniques。只有当第一个位置参数不是对象时,它才能正常工作。我想提出以下几个习语之一:
function foo(a, b) { // positional is normal case
if (arguments.length == 1 && typeof arguments[0] == "object")
{a, b} = arguments[0];
console.log(a, b);
}function foo({a, b}) { // named is normal case
if (arguments.length > 1 || typeof arguments[0] != "object")
[a, b] = arguments;
console.log(a, b);
}如果您需要默认值,那么无论哪种方法,它都会变得很难看:
function foo(a, b) {
var opts = (arguments.length == 1 && typeof arguments[0] == "object")
? arguments[0]
: {a, b};
({a = 'peanut', b = 'butter'} = opts);
console.log(a, b);
}发布于 2015-12-17 06:31:05
我想像这样的事情会奏效的:
function foo(...options){
if (typeof options[0] === 'object'){
console.log('expect object', options[0]);
}else{
console.log('expect array', options);
}
}
foo('peanut', 'butter');
foo({a:'peanut', b:'butter'});发布于 2015-12-17 10:42:28
我不认为这是内置的东西,但这段代码应该适用于你的情况
function foo({a = 'peanut', b = 'butter'} = {}) {
if (typeof arguments[0] === 'string') {
return foo({a: arguments[0], b: arguments[1]})
}
console.log(a, b);
}https://stackoverflow.com/questions/34327844
复制相似问题