Pass the value to a specific parameter without worrying about the position of the parameter

I was wondering if it is possible to pass a value to a specific parameter, for example, by specifying its name, not taking into account whether this parameter is the first, second or 100th.

For example, in Python, you can do this easily:

def myFunction(x, y): pass myFunction(y=3); 

I really need to pass the value to a specific parameter, which I do not know about, its position in the parameter enumeration is mandatory. I searched around for a while, but nothing works.

+3
source share
6 answers

No, named parameters do not exist in javascript.

There is a (kind of) workaround, often a complex method can take an object instead of individual parameters

 function doSomething(obj){ console.log(obj.x); console.log(obj.y); } 

can be called with

 doSomething({y:123}) 

That would first log undefined ( x ), followed by 123 ( y ).

You can allow some parameters to be optional and provide default values ​​if they are not specified:

 function doSomething(obj){ var localX = obj.x || "Hello World"; var localY = obj.y || 999; console.log(localX); console.log(localY); } 
+5
source

Passing parameters in JavaScript is not possible. If you need to do this, you better pass the object to your function, whose properties will be represented by the parameters you want to pass:

 function myFunction(p) { console.log(px); console.log(py); } myFunction({y:3}); 
+3
source
 function myFunction(parameters) { ... var x = parameters.myParameter; } myFunction({myParameter: 123}); 
+2
source

I do not think this function exists in JavaScript

An alternative way is

 function someFun(params) { var x = prams.x; ... } 

The function call will look like

 someFun({x: 5}); 
+2
source

No, but you can pass an object to achieve this.

 var myFunction = function(data){ console.log(data.foo); //hello; console.log(data.bar); //world; } myFunction({foo: 'hello', bar: 'world'}); 

EDIT

Otherwise, your parameters will be received by ORDER, not by name.

 var myFunction = function(foo, bar){ console.log(foo); //bar; console.log(bar); //foo; //hyper confusing } var foo = 'foo', bar = 'bar'; //Passing the parametes out of order myFunction(bar, foo); 
0
source

There are no named parameters in Javascript.

But if you do not call a system or compressed function, you can still call it by argument name.

The following is an idea on how to do this:

 function myFunction(x, y) { return x + y } function invokeByParams(func, params) { var text = func.toString() var i1 = text.indexOf('(') + 1 var i2 = text.indexOf(')') var args = text.substring(i1, i2).split(',') args = args.map(function(x) { return x.trim() }) args = args.map(function(x) { return params[x.trim()] }) return func.apply(this, args) } invokeByParams(myFunction, { y: 1, x: 2 }) // => 6 
0
source

Source: https://habr.com/ru/post/1275537/


All Articles