对不起,如果这是转帖,但我还没有找到答案
假设您有以下功能:
function calculus(a, b = 2, c = 3) {
return a + b - c;
}
我想要做的是为参数 a 和 c 传递新值,而不必编辑 b
所以我写了我在以下代码段中尝试过的方法
function calculus(a, b = 2, c = 3) {
return a + b - c;
}
document.body.append("Case 1: Result " + calculus(2))
document.body.appendChild(document.createElement("br"));
document.body.append("Case 2: Result " + calculus(2, 2, 2))
document.body.appendChild(document.createElement("br"));
document.body.append("Csse 3: Result " + calculus(2, c = 2))
document.body.appendChild(document.createElement("br"));
// next line syntax error
//document.body.append("Case 4:" + calculus(2, c : 3))
所以在函数调用“c=2”或“c:2”中写入不会产生与案例2相同的结果
有什么语法可以用来做到这一点吗?所以只传递 a 和 c 作为参数并省略 b,仍然得到与案例 2 相同的结果?
如果没有,您会使用哪些解决方法?也许是一个带有属性作为参数的对象?
只需传递undefined
要省略的参数:
function calculus(a, b = 2, c = 3) {
return a + b - c;
}
document.body.append("Case 1: Result " + calculus(2))
document.body.appendChild(document.createElement("br"));
document.body.append("Case 2: Result " + calculus(2, 2, 2))
document.body.appendChild(document.createElement("br"));
document.body.append("Case 3: Result " + calculus(2, undefined, 2))
document.body.appendChild(document.createElement("br"));
document.body.append("Case 4: Result " + calculus(2, undefined, 3))
您还可以使用允许[2,,3]
传递的数组参数:
function calculus([a, b = 2, c = 3]) {
return a + b - c;
}
document.body.append("Case 1: Result " + calculus([2]))
document.body.appendChild(document.createElement("br"));
document.body.append("Case 2: Result " + calculus([2, 2, 2]))
document.body.appendChild(document.createElement("br"));
document.body.append("Case 3: Result " + calculus([2,,2]))
document.body.appendChild(document.createElement("br"));
document.body.append("Case 4: Result " + calculus([2,,3]))
一个对象会以同样的方式工作:
function calculus({a, b = 2, c = 3}) {
return a + b - c;
}
document.body.append("Case 1: Result " + calculus({a: 2}))
document.body.appendChild(document.createElement("br"));
document.body.append("Case 2: Result " + calculus({a: 2, b:2, c:2}))
document.body.appendChild(document.createElement("br"));
document.body.append("Case 3: Result " + calculus({a: 2, c: 2}))
document.body.appendChild(document.createElement("br"));
document.body.append("Case 4: Result " + calculus({a: 2, c: 3}))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句