var temp = Testing(A, B, C, D);
In the above case I need inside the function parameters list. (i.e., A,B,C,D) in array list. (i.e., arr[0]=A, arr[1]=B etc.,).
Thanks & Advance....
As per my understanding from question, you want to say how to pass array as parameter in function. So probably you can do it like
var A=['a','v','c','d'];
var a = function(Arr)
{
for(var i=0;i<Arr.length;i++)
{
console.log("element",Arr[i]);
};
};
a(A);
The arguments object is a local variable available within all functions.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
var Testing = function() {
alert(arguments[0]);
}
var temp = Testing(1,2,3,4);
Related
I need to call a function with the same parameter's values to refresh a ChartJs with a new daterange.
The _reportDateStart and _reportDateEnd are updated outside of the function, so I need to recall the function so the chart is updated with the new data.
The script is:
var _reportDateStart;
var _reportDateEnd;
var _loadChart = function (chartLabel, queryMetrics, queryDimensions) {}
The call is made like this:
_loadChart("Visits", "ga:sessions", "ga:date,ga:nthDay");
But can also be:
_loadChart("Users", "ga:users", "ga:date,ga:nthDay");
Declare globally accessible variables and assign the parameters on every call that way you can call the function with those variables again:
Example:
var param1,param2,param3;
var _loadChart = function(a, b, c){
param1 = a;
param2 = b;
param3 = c;
//rest of the code.
};
function callTheFunctionAgain(){
_loadChart(a, b, c);
}
_loadChart("Visits", "ga:sessions", "ga:date,ga:nthDay");
callTheFunctionAgain();
to do this you can create a new function with bound param as you wish like this var _loadChartBounded = _loadChart.bind(null, "Visits", "ga:sessions", "ga:date,ga:nthDay")
then every time you call _loadChartBounded() it will get the same param
We already have global variables and .bind()
I will throw in another solution which uses a closure
For an explanation on how these work, head over to this question and its excellent answers:
How do JavaScript closures work?
// This is only an example.
// Please change the variable names to something more meaningful :)
var _loadContent = (function() {
var _a, _b, _c;
return function(a, b, c) {
if (typeof _a === "undefined") {
_a = a;
_b = b;
_c = c;
}
console.log(_a, _b, _c);
}
}());
_loadContent(1, 2, 3);
_loadContent(4, 5, 6);
_loadContent();
For those arriving in the now (15 Jun 2020), here's the most robust way to call a function from within it:
let fn = (a, b, c) => {
/* fn's content */
fn(...arguments);
}
This works great if you don't know what the parameters will be (user input), or simply do not want to have to change the parameters in multiple places when refactoring the code.
Reference
I need to achieve following in my Node.js program.
How create a function array from their names provided in strings?
How to execute those functions one after another. Not asynchronously.
How to pass parameters for those functions.
Suggest me a better approach to achieve this or code snippet somewhere already implemented this.
You can do like this;
function foo(v){console.log("foo: ",v)};
function bar(v){console.log("bar: ",v)};
var funs = ["foo", "bar"],
i = 0;
while (i < funs.length) this[funs[i]](i++);
Well of course your functions definitions might reside in a particular scope and you may need to invoke them from within whatnot..! In that case you can of course wrap the above code in a function and bind it to whatever scope your function definitions are made in. Such as
var obj = {
foo: function(v){console.log("foo: ",v)},
bar: function(v){console.log("bar: ",v)}
},
funs = ["foo", "bar"],
runner = function(a){
var i = 0;
while (i < a.length) this[a[i]](i++);
}.bind(obj);
runner(funs);
Step 1. Define the list
var functions = ["foo", "bar", "baz"];
Step 2. Iterate the list
We iterate over the function list and call the __call function.
functions.forEach(function(f){
__call(f);
});
Step 3. Call the function
This step is dependent on framework. If you're using node, you have to use the global object. If you're using a browser (HTML) you have to use the window object.
For the former, use:
__call = function(f) {
var args = [];
for(var i = 1; i<arguments.length; i++){
args.push(arguments[i])
};
console.log(args);
global[f].apply(null, args);
};
For the latter, use:
__call = function(f) {
var args = [];
for(var i = 1; i<arguments.length; i++){
args.push(arguments[i])
};
console.log(args);
window[f].apply(null, args);
};
The only difference is we're using the window or global dictionary to access the function.
EDIT: Added passing parameters.
You can call a function by its name like this:
const functions = ['index', 'push'...];
functions[0]() // write your parameters inside. this will call 'index'
If those function are not async, just write the callings one after another. If they are async, use a helper like async.waterfall or async.series.
see 1.
I have a problem when trying to give an array (or variable) a new value. Inside a function, I want to give a new value to a variable pointed out by the parameters when executing the function.
var a = 0;
var b = 0;
function editvariable (target, newValue) {
var target = newValue;
}
editvariable(a, 4);
In this example, I want to change the value of a to 4, but it will only make a new function called target.
a is defined out of the function scope, so you can simply set a = newValue
But why would you want to make a function for what a simple assignment statement can do?
If you really want to have target re-assign a, you'll have to return the result.
var a=0;
var b=0;
function editvariable(target,newValue){
target=newValue;
return target; //return the assignment
}
a = editvariable(a,4)
var target=newValue;
Just remove var.
Since I can determine the number of arguments a function expects to have by calling its Function.length property, is there any way for me to programmatically create the right number of parameters to insert into that function at runtime? Example:
var xyz = function(a,b) {};
var bcd = function(a,b,c,d,e,f) { }; // vararg example
var doc = document, func_length = xyz.length;
doc.xyz = (function() {
return function(a,b,c,d,e) { /* works for one but not the other */ } }).call(doc);
/* would prefer to `return function(a,b)` with only 2 parameters, if it is
used for function `xyz` (though returning 5 works fine in this case), and to
`return function(a,b,c,d,e,f)` with 6 if used for function `bcd` (which does
not work with only five params). */
// thinking about xyz.apply(null,arguments)...but which arguments..? :(
// Returning function(a,b,c,d,e) does not support functions with more than five
// parameters...which would mostly be varargs - hence my question
// I am also well aware that I can use an object or an array instead of
// using many params.
/* This is for incorporating a user-defined function for use in my code, while
* allowing for my function to do 'other stuff' afterward. (And allowing for
* varargs, of course).
* Because coding something like: doc.xyz = xyz is inflexible */
As you can see, I don't know how to do this, or if it is even possible. The search bar hasn't given me any other questions like this one, otherwise I would not have asked...
NOTE: This answer is a product of misunderstanding but
may help the future visitors of this site.
Another way:
Do you really need to add parameters? Writing the function this way would be enough:
function foo(){ //No arguments predefined
a = arguments[0] || ""; //first argument or (if not defined) empty string
b = arguments[1] || ""; //second argument etc.
c = arguments[2] || ""; //third argument etc.
alert(a+b+c);
}
foo("Hello ", "world!");
This alerts "Hello world".
The solution you want:
The simplest way:
This is what you've asked for but it's not as simple as the previous solution.
You can define a meta function with all the parameters and a handler function that changes over the time.
(function(){ //Wrapper
var foo_meta = function(a,b,c,d){ //Local meta of foo
alert(a+b+c+d); //Do the code
};
window.foo = function(a,b){ //Global foo
return foo_meta(a,b,"","");
};
window.redefine_foo = function(){ //Global foo-changer
//Rewrites foo
window.foo = function(a,b,c){
return foo_meta(a,b,c,"");
};
};
})(); //Wrapper
//Do some code
foo("a","b");
redefine_foo(); //Rewrite foo
foo("a","b","c");
//Note that foo_meta is not defined here
foo_meta == undefined; //It's safe in the wrapper :)
This will alert "ab" and then "abc". For the meaning of wrapper function, see the references.
Reference:
Arguments array: http://goo.gl/FaLM1H
Wrapping code: http://goo.gl/uQ5sd0
If you send two parameters 6 and 7 to a function doWork(a,b,c,d,e),a=7 and b=6 will be automatically set and rest of the parameters will be ignored.
Why not just pass one object into the function and use JQuery extend.
e.g.
var parm =
{ x: 1, y : 2};
f(p) {
p = $_.extend({...defaults here}, p);
...
}
This is an example for joining the arguments, regardless of the number of arguments, to show how function arguments can be turned into an array and then processed like any other array.
function foo(){ //No arguments predefined
// convert to real array
var args = Array.prototype.slice.call(arguments);
// or if Array generics are available
var args = Array.slice(arguments);
console.log(args.join(' '));
}
foo('Hello', 'world!');
foo('Hello', 'wonderful', 'world!');
Here is the fiddle
Ref: arguments MDN
Well, I think I've figured it out at last. I've realized that there may be no way to 'truly' add a parameter to a function the way that I was asking, but there is a way to emulate the same result:
var doc = document;
var xyz = function(a,b) {};
var bcd = function(a,b,c,d,e,f) {};
var obj = {};
// Now, here it is (mostly (sort of)):
obj.userFunc = function(args) {
var args_Array = [];
for (var i=0;i < arguments.length; i++ ) {
args_Array.push(arguments[i])
}
xyz.apply(null,args_Array); // or 'this'. or 'undefined'. Whatever you want.
// do other stuff
return this; // we know what to do to make 'this' scope explicit
} // end
var thisFunc = 'xyz'
doc[thisFunc] = obj.userFunc;
doc.xyz('h','i');
doc.xyz('h','i','j');
doc.xyz('h','i','j','k');
doc.xyz('h','i').xyz('j','l').xyz('j','q'); // etc.
The trick was to use the arguments object, which conveniently assimilated all the parameters into a readily available object, push each value into an array then apply the function.
In case you're wondering what the fuss was all about, I wanted to completely incorporate a user-defined function into another function, while still being able to do 'other stuff' afterward. My previous example worked to an extent, but did not have support for varargs. This does.
This approach is greatly more flexible than: doc[thisFunc] = userDefinedFunction
:) 4/26/2014
This is a hacky question of JavaScript.
For instance, we have a function as below:
var f1 = function(a,b)
{
return a + b;
};
and now, I want this (or another) function generated by a factory function with a template described in an array, like this:
var fCode = [a, b, a+b];
var functionFactory = function(fCode)
{
//........
return f;
};
var f1 = functionFactory(fCode);
I understand that functionFactory is consequently a closure form, and my question is not that point.
I've tried object wrapper etc., but so far have not been able to find a clean implementation.
Any thoughts? Thanks.
The only way I can see to achieve what I think you are asking for is use the built in Function constructor.
You can create a new function by passing in parameter names and a function body like so:
var f1 = new Function("a", "b", "return a+b;");
f1(2,2); // 4
If you combine that with the built in apply method you can use an array as a sort of "template"
var template = ["a", "b", "return a+b;"];
var f1 = Function.apply(undefined, template);
f1(2,2); // 4
The first argument to apply is what is bound to the this pointer when invoking that function. If you leave it undefined it will be the global object.