我想根据参数是否未定义返回不同的语句。问题是,如果假设缺少第二个参数,则第三个参数"成为"第二个参数,因此无论缺少哪个参数,我都只点击最后一个 else if 语句(仅当最后一个参数丢失时才适用)。我已经研究过,但找不到解决方案。我尝试使用
var array=Array.prototype.slice.call(arguments);
然后检查数组[0],数组[1]和数组[2],但这也不起作用,因为我总是得到"c不存在" 任何帮助将不胜感激。谢谢
function testing(a, b, c) {
if (a === undefined) {
return 'a doesnt exist'
} else if (b === undefined) {
return 'b doesnt exist'
} else if (c === undefined) {
return 'c doesnt exist'
}
}
testing(3, 'name')
如果调用方只使用两个参数调用函数,则不知道缺少的是第二个参数还是第三个参数,除非您可以从预期的类型推断出它。 例如,如果您希望b
是一个数字,而c
是一个函数,那么:
if (typeof b === "function") {
// `b` was omitted (effectively)
c = b;
b = undefined;
}
但是,如果您期望b
和c
具有相同类型的参数,或者您允许它们使用任何类型的参数,那么您就无法知道仅提供两个参数的调用方是否意味着提供a
和b
或a
和c
。
在这种情况下,你必须记录函数,说如果你想(有效地)省略b
,你需要为它提供undefined
:testing(1, undefined, 3);
(这样做与ES2015的默认参数配合得很好,而完全省略它则不然。
接受复杂参数组合的另一种方法,它接受对象而不是离散参数:
function testing(options) {
console.log("a:", options.a);
console.log("b:", options.b);
console.log("c:", options.c);
}
// Usage
testing({a: 1, c: 3});
如果你这样做了,并且如果你可以使用ES2015(又名"ES6")功能(例如,你只针对尖端浏览器,或者你正在转译),你可以使用参数解构来让它们自动映射到你的参数:
function testing({a, b, c}) {
console.log("a:", a);
console.log("b:", b);
console.log("c:", c);
}
// Usage
testing({a: 1, c: 3});
您甚至可以将其与默认参数值结合使用:
function testing({a = 1, b = 2, c = 3}) {
console.log("a:", a);
console.log("b:", b);
console.log("c:", c);
}
// Usage
testing({a: 1, c: 3});
或者只是确保使用所有三个参数调用函数,例如:
testing(3, undefined, 'name');