[英]JavaScript function - named parameters issue when skipping an optional parameter
If you run the below code in browser's console: 如果您在浏览器的控制台中运行以下代码:
function named_param(a, b=null, c=5) {
console.log("a="+a);
console.log("b="+b);
console.log("c="+c);
}
named_param(3, c=10)
The output received is: 收到的输出是:
a=3
b=10
c=5
The output I am looking for, is: 我正在寻找的输出是:
a=3
b=null
c=10
I saw the below two URLs and tried a few workaround but it didn't work 我看到了以下两个URL,并尝试了一些解决方法,但没有成功
Javascript Function Parameters Not Working JavaScript函数参数不起作用
Named parameters in javascript JavaScript中的命名参数
Let me know the steps I am doing wrong here. 让我知道我在这里做错的步骤。 Tried the below codes but didn't work: A:
尝试了以下代码,但没有用:A:
function named_param(a, {b=null, c=5}) {
console.log("a="+a);
console.log("b="+b);
console.log("c="+c);
}
named_param(3, c=10)
B: B:
function named_param(a, {b=null, c=5}={}) {
console.log("a="+a);
console.log("b="+b);
console.log("c="+c);
}
named_param(3, c=10)
You can skip parameter in between, so when you pass 您可以在两者之间跳过参数,因此当您通过时
named_param(3, c=10)
| |_____________ considered as `b`
|_________________ considered as `a`
You can use object and destructuring 您可以使用对象和解构
function named({a,b=null,c=3} = {}){ console.log('a-->',a) console.log('b-->',b) console.log('c-->',c) } named({a:1,c:2}) named() named({c:2})
When using the destructuring solution, you must pass an actual object. 使用解构解决方案时,必须传递实际对象。
named_param(3, c=10)
simply is invalid syntax (well, it's valid, but it's an assignment to a global c
variable that is passed as the second argument - no naming). named_param(3, c=10)
只是无效的语法(嗯,它是有效的,但这是对全局c
变量的赋值,该变量作为第二个参数传递-没有命名)。
function named_param(a, {b=null, c=5}={}) {
console.log("a="+a);
console.log("b="+b);
console.log("c="+c);
}
named_param(3)
named_param(3, {b:"hi"})
named_param(3, {c:10})
named_param(3, {b:"hi", c:10})
What you can do is something using destructuring objects like: 您可以做的是使用解构对象,例如:
function named_params({a = 4, b = null, c = 5} = {a:1, b: 2, c:3}) { console.log(a,b,c) }
then, the call for your function will be: 然后,对您的函数的调用将是:
named_params({a: 3, c:10})
Well, it's not an issue, it's just you trying to use named parameters where they are not supported at all. 嗯,这不是问题,只是您尝试使用不支持它们的命名参数。
To reach what you need, you should do like this: 为了达到您的需求,您应该这样做:
function named_param({a, b, c}) {
console.log("a="+a);
console.log("b="+b);
console.log("c="+c);
}
named_param({a:5, c:9});
// Output:
// a=5
// b=undefined
// c=9
At first I misunderstood your question and proposed to use destructuring assignment with arguments
object. 起初,我误解了您的问题,并建议对
arguments
对象使用解构赋值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.