将值传递给特定参数而无需关心参数的位置 [英] Pass a value to a specific parameter without caring about the position of the parameter
问题描述
我想知道是否可以通过例如指定其名称来将值传递给特定参数,而不考虑该参数是第一个,第二个还是第100个.
I was wondering if it is possible to pass a value to a specific parameter by for example specifying its name, not taking into account if this parameter is the first, the second or the 100th one.
例如,在Python中,您可以像这样轻松地做到这一点:
For example, in Python you can do it easily like:
def myFunction(x, y):
pass
myFunction(y=3);
我真的需要将值传递给特定参数,但我不确定该值在参数枚举中的位置.我搜索了一段时间,但似乎没有任何作用.
I really need to pass a value to a specific parameter of which I don't know necessarily its position in the parameters enumeration. I have searched around for a while, but nothing seems to work.
推荐答案
否,javascript中不存在命名参数.
No, named parameters do not exist in javascript.
有一个(多种)解决方法,通常一个复杂的方法可能会用一个对象代替单个参数
There is a (sort of) workaround, often a complex method may take an object in place of individual parameters
function doSomething(obj){
console.log(obj.x);
console.log(obj.y);
}
可以用
doSomething({y:123})
首先记录undefined
(x
),然后记录123
(y
).
Which would log undefined
first (the x
) followed by 123
(the y
).
您也可以允许某些参数为可选参数,并在未提供的情况下提供默认值:
You could allow some parameters to be optional too, and provide defaults if not supplied:
function doSomething(obj){
var localX = obj.x || "Hello World";
var localY = obj.y || 999;
console.log(localX);
console.log(localY);
}
这篇关于将值传递给特定参数而无需关心参数的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!