Javascript pass variable to function name - javascript

I’m trying to create a simple loop of animation functions. I've stored their names in an array and am able to log out each object as a string with a click event. However I can't seem to call the corresponding functions of that event
I've tried to do this but I get an error nt[rt] is not a function
arrAnimations[activeScene]()
I've tried many approaches from stack overflow from similar questions, such as creating a helper function like this
myFunction = function(){};
var arrAnimations = {italy: myFunction};
arrAnimations['activeScene']();//executes the function
and this
var tmp = arrAnimations[activeScene]
window[tmp]
Here is the code:
var arrAnimations = [
'italy',
'czech',
'russia'
]
var activeScene = 0;
document.getElementById('animate').addEventListener("click",
function incNumber() {
if (activeScene < arrAnimations.length - 1) {
activeScene++;
} else if (activeScene = arrAnimations.length - 1) {
activeScene = 0;
}
// console.log(arrAnimations[activeScene])
}
)
function italy() { console.log('italy') }
function czech() { console.log('czech') }
function russia() { console.log('russia') }
<div id="animate">Animate</div>

The array can store the actual functions themselves, instead of the function names.
function italy() { console.log('italy') }
function czech() { console.log('czech') }
function russia() { console.log('russia') }
var arrAnimations = [ italy, czech, russia ]
Then locate the item in the array, and call it:
var activeScene = 0;
arrAnimations[activeScene]()
Demo in Stack Snippets
function italy() { console.log('italy') }
function czech() { console.log('czech') }
function russia() { console.log('russia') }
var arrAnimations = [ italy, czech, russia ]
var index = 0;
function callNextFunction() {
index = index >= arrAnimations.length - 1 ? 0 : index + 1
arrAnimations[index]()
}
var btn = document.getElementById('animate')
btn.addEventListener("click", callNextFunction)
<button id="animate">Animate</button>

In your commented out line:
console.log(arrAnimations[activeScene])
You're trying to call a method on the array, which doesn't exist. It's an array of strings. Instead, you need to get the string value, then use that to call a method on the window.
window[arrAnimations[activeScene]]();
With that said though, I'd make your code a bit simpler and use lambda functions, and avoid a couple of if statements, try this:
<div id="animate">Animate</div>
<script>
var arrAnimations = [
() => console.log('italy'),
() => console.log('czech'),
() => console.log('russia')
]
var activeScene = 0;
document.getElementById('animate').addEventListener('click', () => {
arrAnimations[activeScene]();
activeScene++;
activeScene = activeScene % arrAnimations.length;
});
</script>

italy = () => console.log('italy')
czech = () => console.log('czech')
russia = () => console.log('russia')
if Array of functions:
let arrAnimationsAsFunctions = [ italy , czech , russia];
arrAnimationsAsFunctions.forEach(animation => animation())
if Array of Strings:
let arrAnimationsAsStrings = [ 'italy' , 'czech' , 'russia' ];
arrAnimationsAsStrings.forEach(animation => eval(animation)())
use eval to run a string as JS code

Is this what you want?
foo = () => console.log('foo')
bar = () => console.log('bar')
baz = () => console.log('baz')
fns = {
foo,
bar,
baz
}
Object.keys(fns).forEach(fn => fns[fn]())
fns['foo']()
fns['bar']()
Note: you can't cast a string to a function like this, at least in Javascript:
let fn = () => {}
let foo = 'fn'
foo() // X
// foo is a string, not a function, It is just a coincidence that the content of the string is same with the function's name

Related

Using function of an object after grabbing it from array

When I try to grab the object from the array, the type is undefined. Therefore I cannot use a method from the undefined object as it doesn't exist. I am relatively new to JavaScript and I have come straight from Java so the way of retrieving objects is kind of new to me. This is what I currently have.
var fleetAmount = 0;
var fleets = [];
function Fleet(number) {
this.number = number;
this.activities = [];
this.addActivity = function (activity) {
this.activities.push(activity);
};
fleets.push(this);
}
var getFleet = function(fleetNumber) {
return fleets[fleetAmount - fleetNumber];
}
This is where I try to grab the object and preform the function
const Fl = require(‘fleet.js’);
const fleet = Fl.getFleet(fleetNumber);
fleet.addActivity(activity);
I am also working in Node.js, which is how I am using the require method.
In combination with the answer from #audzzy I changed the getFleet() function so that it would be more efficient. I tested it out and it worked. This is what I used
function getFleet(fleetNumber) {
let result = fleets.filter(function (e) {
return e.number = fleetNumber;
})
return result[0];
}
Thanks for the help! I appreciate it.
you want to create a new fleet object and add it, not "this"..
adding "this" would cause a circular reference, where
this.fleets[i] = this (and all fleets would have the same value)
when calling get fleet, I would check that a fleet was returned from get fleet
in case amount is less than the number you send to getFleet (where according to what you posted: 1 returns the last, 2 returns second to last etc..)..
I hope this explanation makes sense.. anyways, this should work..
var fleets = [];
doStuff();
function doStuff(){
addFleet(1);
addFleet(2);
addFleet(7);
addFleet(3);
// should return null
let fleet1 = getFleetByNumber(5);
// should return the fleet with number 7, and not change the fleet with number 1
let fleet2 = getFleetByNumber(7);
if(fleet2){
fleet2.addActivity("activity");
}
console.log(`fleets: ${JSON.stringify(fleets)} \nfleet1: ${JSON.stringify(fleet1)} \nfleet2: ${JSON.stringify(fleet2)}`);
}
function addFleet(number) {
let fleet = { number: number,
activities: [] };
fleet.addActivity = function (activity) {
this.activities.push(activity);
};
fleets.push(fleet);
}
function getFleetByNumber(fleetNumber) {
return fleets.find(function (e) {
return e.number == fleetNumber;
});
}
function getFleet(fleetNumber) {
let result = null;
if(fleets.length - fleetNumber >= 0){
result = fleets[fleets.length - fleetNumber];
}
return result;
}

Which type of variable is created in the code below

In the code below is an iterator:
const cart = ['Product 0','Product 1','Product 2','Product 3','Product 4','Product 5','Product 6','Product 7','Product 8','Product 9','Product 10']
function createIterator(cart) {
let i = 0;//(*)
return {
nextProduct: function() {
//i:0; (**)
let end = (i >= cart.length);
let value = !end ? cart[i++] : undefined;
return {
end: end,
value: value
};
}
};
}
const it = createIterator(cart);
First I know a copy of the present state of the function's variables and the parameters are parsed.(Right?)...
And when you run
const it = createIterator(cart);
Is a property below created?
//i:0 (**);
Making it.next(); equivalent to
{
i:0;//state or value of i from createIterator() definition;
next : function(cart){
let end = (this.i >= cart.length);
let value = !end ? cart[this.i++] : undefined;
return {
end: end,
value: value
};
}
Or does state of the value of i in line (*) from the first code, Is what's what is modified?
Please if this point is not clear... let me know to explain better.
Calling the iterator will create an instance of i scoped to the createIterator function. The object returned from it will only have access to that specific instance of i, but i is not a property of the object returned. It only can access it due to the function scope.
You can see a little better how this works if we break your code down a little more simply:
function createIterator(cart, display) {
let i = 0;
return {
next: function() {
i++;
console.log(display + ' next: ', i);
}
};
}
const cart1 = [];
const cart2 = [];
const it1 = createIterator(cart1, 'cart1');
it1.next();
it1.next();
const it2 = createIterator(cart2, 'cart2');
it2.next();
it2.next();
Each instance of the iterator has a different copy of i and only the object returned from the iterator function can access it.

Test to check if array is reversed in place

I have a method which I have put on the array prototype that reverses the array (this is done for learning purposes only). This method should reverse the array in place.
Array.prototype.yarra = function () {
for (let left=0, right=this.length-1; left<right; left++, right--) {
[this[left], this[right]] = [this[right], this[left]]
}
return this
};
I have written some tests to check if the method works as expected.
describe('yarra', function () {
it('should reverse an array in place and return it', function () {
var arr = [1,2,3];
var reversedArr = arr.yarra();
reversedArr.should.eql([3,2,1]);
arr.should.equal.reversedArr;
[4,5,6].yarra().should.eql([6,5,4]);
});
});
I realise the tests don't work as expected as I reversed the array out of place and returned a new array, and it still passed. Also, because var reversedArr = arr.yarra() means arr will always equal reversedArr, so it doesn't really check for anything.
How would I write a test that can check if the array is reversed in place?
const assert = require('assert');
Array.prototype.yarra = function () {
for (let left=0, right=this.length-1; left<right; left++, right--) {
[this[left], this[right]] = [this[right], this[left]]
}
return this
};
describe('yarra1', () => {
it('should reverse an array in place and return it', () => {
let arr = [1,2,3];
let rev = [3,2,1];
let reversedArr = arr.yarra();
for(let i =0;i<arr.length;i++){
assert(reversedArr[i]===rev[i])
}
});
});
describe('yarra2', () => {
it('should reverse an array in place and return it', () => {
let arr = [1,2,3];
let rev = [3,2,1];
let reversedArr = arr.yarra();
assert(reversedArr.toString() === rev.toString())
});
});

Why is my variable undefined inside the Underscore.js each function?

Here is my code:
TextClass = function () {
this._textArr = {};
};
TextClass.prototype = {
SetTexts: function (texts) {
for (var i = 0; i < texts.length; i++) {
this._textArr[texts[i].Key] = texts[i].Value;
}
},
GetText: function (key) {
var value = this._textArr[key];
return String.IsNullOrEmpty(value) ? 'N/A' : value;
}
};
I'm using the Underscore.js library and would like to define my SetTexts function like this:
_.each(texts, function (text) {
this._textArr[text.Key] = text.Value;
});
but _textArr is undefined when I get into the loop.
In JavaScript, the function context, known as this, works rather differently.
You can solve this in two ways:
Use a temporary variable to store the context:
SetTexts: function (texts) {
var that = this;
_.each(texts, function (text) {
that._textArr[text.Key] = text.Value;
});
}
Use the third parameter to _.each() to pass the context:
SetTexts: function (texts) {
_.each(texts, function (text) {
this._textArr[text.Key] = text.Value;
}, this);
}
You have to pass this as context for _.each call like this:
_.each(texts, function (text) {
this._textArr[text.Key] = text.Value;
}, this);
See the docs for http://underscorejs.org/#each
this in javascript does not work the same way as you would expect. read this article:
http://www.digital-web.com/articles/scope_in_javascript/
short version:
the value of this changes every time you call a function. to fix, set another variable equal to this and reference that instead
TextClass = function () {
this._textArr = {};
};
TextClass.prototype = {
SetTexts: function (texts) {
var that = this;
for (var i = 0; i < texts.length; i++) {
that._textArr[texts[i].Key] = texts[i].Value;
}
},
GetText: function (key) {
var value = this._textArr[key];
return String.IsNullOrEmpty(value) ? 'N/A' : value;
}
};
Note that you can also pass things other that "this". For example, I do something like:
var layerGroupMasterData = [[0],[1,2,3],[4,5],[6,7,8,9],[10]];
_.each(layerGroupMasterData,function(layerGroup,groupNum){
_.each(layerGroup, function (layer, i) {
doSomethingThatComparesOneThingWithTheOverallGroup(layerGroupMasterData,layer);
},layerGroups);
},layerGroupMasterData);

Javascript Array of Functions

var array_of_functions = [
first_function('a string'),
second_function('a string'),
third_function('a string'),
forth_function('a string')
]
array_of_functions[0];
That does not work as intended because each function in the array is executed when the array is created.
What is the proper way of executing any function in the array by doing:
array_of_functions[0]; // or, array_of_functions[1] etc.
Thanks!
var array_of_functions = [
first_function,
second_function,
third_function,
forth_function
]
and then when you want to execute a given function in the array:
array_of_functions[0]('a string');
I think this is what the original poster meant to accomplish:
var array_of_functions = [
function() { first_function('a string') },
function() { second_function('a string') },
function() { third_function('a string') },
function() { fourth_function('a string') }
]
for (i = 0; i < array_of_functions.length; i++) {
array_of_functions[i]();
}
Hopefully this will help others (like me 20 minutes ago :-) looking for any hint about how to call JS functions in an array.
Without more detail of what you are trying to accomplish, we are kinda guessing. But you might be able to get away with using object notation to do something like this...
var myFuncs = {
firstFunc: function(string) {
// do something
},
secondFunc: function(string) {
// do something
},
thirdFunc: function(string) {
// do something
}
}
and to call one of them...
myFuncs.firstFunc('a string')
I would complement this thread by posting an easier way to execute various functions within an Array using the shift() Javascript method originally described here
var a = function(){ console.log("this is function: a") }
var b = function(){ console.log("this is function: b") }
var c = function(){ console.log("this is function: c") }
var foo = [a,b,c];
while (foo.length){
foo.shift().call();
}
Or just:
var myFuncs = {
firstFun: function(string) {
// do something
},
secondFunc: function(string) {
// do something
},
thirdFunc: function(string) {
// do something
}
}
It's basically the same as Darin Dimitrov's but it shows how you could use it do dynamically create and store functions and arguments.
I hope it's useful for you :)
var argsContainer = ['hello', 'you', 'there'];
var functionsContainer = [];
for (var i = 0; i < argsContainer.length; i++) {
var currentArg = argsContainer[i];
functionsContainer.push(function(currentArg){
console.log(currentArg);
});
};
for (var i = 0; i < functionsContainer.length; i++) {
functionsContainer[i](argsContainer[i]);
}
up above we saw some with iteration. Let's do the same thing using forEach:
var funcs = [function () {
console.log(1)
},
function () {
console.log(2)
}
];
funcs.forEach(function (func) {
func(); // outputs 1, then 2
});
//for (i = 0; i < funcs.length; i++) funcs[i]();
Ah man there are so many weird answers...
const execute = (fn) => fn()
const arrayOfFunctions = [fn1, fn2, fn3]
const results = arrayOfFunctions.map(execute)
or if you want to sequentially feed each functions result to the next:
compose(fn3, fn2, fn1)
compose is not supported by default, but there are libraries like ramda, lodash, or even redux which provide this tool
This is correct
var array_of_functions = {
"all": function(flag) {
console.log(1+flag);
},
"cic": function(flag) {
console.log(13+flag);
}
};
array_of_functions.all(27);
array_of_functions.cic(7);
If you're doing something like trying to dynamically pass callbacks you could pass a single object as an argument. This gives you much greater control over which functions you want to you execute with any parameter.
function func_one(arg) {
console.log(arg)
};
function func_two(arg) {
console.log(arg+' make this different')
};
var obj = {
callbacks: [func_one, func_two],
params: ["something", "something else"];
};
function doSomething(obj) {
var n = obj.counter
for (n; n < (obj.callbacks.length - obj.len); n++) {
obj.callbacks[n](obj.params[n]);
}
};
obj.counter = 0;
obj.len = 0;
doSomething(obj);
//something
//something else make this different
obj.counter = 1;
obj.len = 0;
doSomething(obj);
//something else make this different
Execution of many functions through an ES6 callback 🤗
const f = (funs) => {
funs().forEach((fun) => fun)
}
f(() => [
console.log(1),
console.log(2),
console.log(3)
])
Using ES6 syntax, if you need a "pipeline" like process where you pass the same object through a series of functions (in my case, a HTML abstract syntax tree), you can use for...of to call each pipe function in a given array:
const setMainElement = require("./set-main-element.js")
const cacheImages = require("./cache-images.js")
const removeElements = require("./remove-elements.js")
let htmlAst = {}
const pipeline = [
setMainElement,
cacheImages,
removeElements,
(htmlAst) => {
// Using a dynamic closure.
},
]
for (const pipe of pipeline) {
pipe(htmlAst)
}
A short way to run 'em all:
[first_function, ..., nth_function].forEach (function(f) {
f('a string');
});
the probleme of these array of function are not in the "array form" but in the way these functions are called... then...
try this.. with a simple eval()...
array_of_function = ["fx1()","fx2()","fx3()",.."fxN()"]
var zzz=[];
for (var i=0; i<array_of_function.length; i++)
{ var zzz += eval( array_of_function[i] ); }
it work's here, where nothing upper was doing the job at home...
hopes it will help
Using Function.prototype.bind()
var array_of_functions = [
first_function.bind(null,'a string'),
second_function.bind(null,'a string'),
third_function.bind(null,'a string'),
forth_function.bind(null,'a string')
]
I have many problems trying to solve this one... tried the obvious, but did not work. It just append an empty function somehow.
array_of_functions.push(function() { first_function('a string') });
I solved it by using an array of strings, and later with eval:
array_of_functions.push("first_function('a string')");
for (var Func of array_of_functions) {
eval(Func);
}
maybe something like this would do the trick:
[f1,f2,f3].map((f) => f('a string'))
Maybe it can helps to someone.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
window.manager = {
curHandler: 0,
handlers : []
};
manager.run = function (n) {
this.handlers[this.curHandler](n);
};
manager.changeHandler = function (n) {
if (n >= this.handlers.length || n < 0) {
throw new Error('n must be from 0 to ' + (this.handlers.length - 1), n);
}
this.curHandler = n;
};
var a = function (n) {
console.log("Handler a. Argument value is " + n);
};
var b = function (n) {
console.log("Handler b. Argument value is " + n);
};
var c = function foo(n) {
for (var i=0; i<n; i++) {
console.log(i);
}
};
manager.handlers.push(a);
manager.handlers.push(b);
manager.handlers.push(c);
</script>
</head>
<body>
<input type="button" onclick="window.manager.run(2)" value="Run handler with parameter 2">
<input type="button" onclick="window.manager.run(4)" value="Run handler with parameter 4">
<p>
<div>
<select name="featured" size="1" id="item1">
<option value="0">First handler</option>
<option value="1">Second handler</option>
<option value="2">Third handler</option>
</select>
<input type="button" onclick="manager.changeHandler(document.getElementById('item1').value);" value="Change handler">
</div>
</p>
</body>
</html>
This answered helped me but I got stuck trying to call each function in my array a few times. So for rookies, here is how to make an array of functions and call one or all of them, a couple different ways.
First we make the array.
let functionsArray = [functionOne, functionTwo, functionThree];
We can call a specific function in the array by using its index in the array (remember 0 is the first function in the array).
functionsArray[0]();
We have to put the parenthesis after because otherwise we are just referencing the function, not calling it.
If you wanted to call all the functions we could use a couple different ways.
For loop
for (let index = 0; index < functionsArray.length; index++) {
functionsArray[index]();
}
Don't forget the parenthesis to actually call the function.
ForEach
ForEach is nice because we don't have to worry about the index, we just get handed each element in the array which we can use. We use it like this (non arrow function example below):
functionsArray.forEach(element => {
element();
});
In a ForEach you can rename element in the above to be whatever you want. Renaming it, and not using arrow functions could look like this:
functionsArray.forEach(
function(funFunctionPassedIn) {
funFunctionPassedIn();
}
);
What about Map?
We shouldn't use Map in this case, since map builds a new array, and using map when we aren't using the returned array is an anti-pattern (bad practice).
We shouldn't be using map if we are not using the array it returns, and/or
we are not returning a value from the callback. Source
I know I am late to the party but here is my opinion
let new_array = [
(data)=>{console.log(data)},
(data)=>{console.log(data+1)},
(data)=>{console.log(data+2)}
]
new_array[0]
you got some top answers above. This is just another version of that.
var dictFun = {
FunOne: function(string) {
console.log("first function");
},
FuncTwo: function(string) {
console.log("second function");
},
FuncThree: function(string) {
console.log("third function");
}
}
/* PlanetGreeter */
class PlanetGreeter {
hello : { () : void; } [] = [];
planet_1 : string = "World";
planet_2 : string = "Mars";
planet_3 : string = "Venus";
planet_4 : string = "Uranus";
planet_5 : string = "Pluto";
constructor() {
this.hello.push( () => { this.greet(this.planet_1); } );
this.hello.push( () => { this.greet(this.planet_2); } );
this.hello.push( () => { this.greet(this.planet_3); } );
this.hello.push( () => { this.greet(this.planet_4); } );
this.hello.push( () => { this.greet(this.planet_5); } );
}
greet(a: string) : void { alert("Hello " + a); }
greetRandomPlanet() : void {
this.hello [ Math.floor( 5 * Math.random() ) ] ();
}
}
new PlanetGreeter().greetRandomPlanet();

Categories

Resources