This question already has answers here:
Is there a way to provide named parameters in a function call in JavaScript?
(12 answers)
How to get function parameter names/values dynamically?
(34 answers)
Closed 4 years ago.
I have many functions defined elsewhere that look like this
export function foo(bar1, bar2, bar3, ...) {
// does stuff
}
In the module I am working on I am passed both the function above and an object containing the parameters like this:
// params = {
// bar1: bar1Value,
// bar2: bar2Value,
// bar3: bar3Value,
// ...
// }
function myFunc(foo, params) {
}
I need to call func with the params in the correct order. It is an object not an array so I can't rely on the property order, I need to match up the params to the signature of the function. Is this possible?
Edit to add: There are hundreds of functions that can be passed in, I am trying to avoid refactoring them all, but it seems that it is impossible to look up the parameter names directly. However I've found this which shows it can be done by breaking down the function as a string.
You can access the properties of an object (like "params") either like
params.bar1 or like params["bar1"] and you can get the names of the properties by using Object.keys(params), if thats what your asking for.
See also https://www.w3schools.com/js/js_object_properties.asp and https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
Related
This question already has answers here:
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Closed 5 months ago.
There is a way to pass a string in a function to other function and this string is a reference to an object in this other function?
function fun1 (structure){
obj = [{"header":{"orderNumber": a, "item": 1}}, {"header":{"orderNumber": b, "item": 1}}]
newObj = obj[0].structure
console.log(newObj)
//first call a
//second call 1
}
//first call
function fun2(){
structure = 'header.orderNumber'
fun1(structure)
}
//second call
fun2(){
structure = 'header.item'
fun1(structure)
}
What I want is a dynamic way to access an object by creating a string.
For example in the block of code obj.header.item.description and this is valid. I would like to pass a string in this string somehow make a reference to the object so I can get the value.
One way you could accomplish this would be by storing all of the object references in a Map (MDN) structure where the key is a string and the value is the object reference in question.
I should say that even though I don't know your exact use case, this is what you would call a "stringly typed" solution which is generally not the best idea.
This question already has answers here:
Is it possible to send a variable number of arguments to a JavaScript function?
(12 answers)
Closed 3 years ago.
I'm new to programming and for the moment I'm learning JavaScript using a combination of online courses. One challenge I'm working on is to use a function to return a random string from an array. That part itself was easy, but it seems like I need to be able to create the array from the input I give when I call the function. As an example, if I were to create a function like this:
function namePicker(names);
And I then called the function and gave it this input:
namePicker("Billy","Timmy","Johnny");
then I should be able to use the input to create an array of these names. However, when I tried to work this into the code for the random name picker, only the first name I gave would return to me.
What am I doing wrong here? Here's the full code I've been working on:
function lunchClubLottery(names) {
var lunchClub = [names];
var randomNumber=Math.floor(Math.random()*lunchClub.length);
return lunchClub[randomNumber];
}
The rest parameter syntax (...) can be used to create an array of all (or some of) the arguments supplied to a function.
function lunchClubLottery(...names) {
var i = Math.floor(Math.random()*names.length)
return names[i]
}
const name = lunchClubLottery("Billy","Timmy","Johnny")
console.log(name)
Or if you want to go old-school, you can use the arguments object (if you are not using a fat arrow function).
Here I convert the array-like arguments object to an Array using slice and call.
function lunchClubLottery() {
const names = Array.prototype.slice.call(arguments)
var i = Math.floor(Math.random()*names.length)
return names[i]
}
const name = lunchClubLottery("Billy","Timmy","Johnny")
console.log(name)
This question already has answers here:
Parameters inside callback function in Javascript
(1 answer)
Higher-Order Functions in JS
(1 answer)
Closed 2 years ago.
I have this code that filters an array using the .filter method.
I'm extremely confused about the function's parameters that is being specified in the .filter method.
Where does the parameter come from? How do I know when to add a parameter like 'value', and what is the value of the parameter 'value'?
var newArray = [1,2,3,4,5,6,7,8,9,10];
newArray = newArray.filter(function(value) {
return value < 6;
});
I'm not too sure if it is the right term to use.
Where does the parameter come from?
It gets passed to the function when the function is called … which will happen somewhere inside filter or a function called by filter.
How do I know when to add a parameter like 'value',
Generally by reading the documentation
what is the value of the parameter 'value'
From the documentation, the first argument is:
element:
The current element being processed in the array.
Array is a JavaScript class and each JavaScript class can have prototype. Filter method is a part of Array prototype and this function is getting as an argument callback function with one argument.
Inside Filter function, your callback is being called on each array item.
You can find more informations about this function in JavaScript docs.
This question already has answers here:
Calling function inside object using bracket notation
(2 answers)
Closed 6 years ago.
I rather have a seemingly trivial issue, but am not able to figure out an efficient approach.
I have a list of about 50 functions to be called such as :
globalClient.funcA(...)
globalClient.funcB(...)
globalClient.funcC(...)
My code should ideally dynamically create the name of the function (funcA / funcB/ funcC and then proceed to actually call that function. My approach below does not work (please note that these aren't exactly the actual names of the functions. I'm only giving these arbitrary names for simplicity of understanding):
var functionName = 'func'.concat('A');
globalClient.functionName
The second line is where it errors out. Now JS thinks that functionName itself is the name of the function. What I want it to do is resolve functionName to funcA and then call globalClient.funcA(...) instead.
I've thought about implementing a switch / case for this but I'm sure there is a far simpler appraoch. Any ideas?
You could use the bracket notation as property accessor.
globalClient[functionName]()
You can use the [ ] operator for accessing the properties.
var globalClient = {
funcA: function(){
console.log('funcA is called');
}
}
var functionName = 'func'.concat('A');
globalClient[functionName]();
This question already has answers here:
Get variable name. javascript "reflection"
(4 answers)
JavaScript: Get Argument Value and NAME of Passed Variable [duplicate]
(7 answers)
Closed 8 years ago.
I was wondering if it's possible to get the name of a variables in javascript or JQuery.
Suppose that I declare a variable in javascript like:
var customerNr = "456910";
If a function receive a variable, how can i return the name of the variable?
For example:
function getNameOfVariable(someVariable){
//return name of someVariable;
}
If I call this function like this:
getNameOfVariable(customerNr);
The function has to return a string whose value is "customerNr".
How can I do this in jquery or javascript? Some kind of reflection?
That is simply not possible!
The passed parameter doesn't even have to have a name. It could be a return value of a function or a raw literal (like "string" or 3).
No, this is not possible. Only values are transferred for primitive data types, not references, so how would you know what the "name" of the variable is? For example:
var customerNr="456910";
var customerNrAfterProcessing=customerNr;
getNameOfVariable(customerNrAfterProcessing);
Would it return customerNrAfterProcessing or customerNr?
However, you can imitate this behavior with objects.
var variableName = someMethodThatDeterminesVariableNameOrJustAConstantIfYouPrefer();
var myVariables={};
var myVariables[variableName]={};
myVariables[variableName].value="456910";
myVariables[variableName].variableName=variableName;
function getNameOfVariable(someVariable){
return someVariable.variableName;
}
getNameOfVariable(myVariables[variableName]);
Obviously, this amounts to a lot more work than just using the variableName variable directly, but it could be necessary in some more complicated situations.
See working with objects in JS reference