using JS; I am passing a function name as an optional argument. I would like to make a switch case that reads the functions name that is being passed. How would I capture the functionVariable as if it were a string "functionVariable"?
Example:
function test(functionVariable)
{
switch(functionVariable)
{
case firstFunction:
alert('1st');
break;
case secondFunction:
alert('2nd');
break;
}
}
When I alert functionVariable, it prints the whole function. It makes sense why but I'm trying to work around it and just get the functions name.
EDIT
Working example
function test(functionVariable)
{
switch(functionVariable.name)
{
case firstFunction:
alert('1st');
break;
case secondFunction:
alert('2nd');
break;
}
}
You could use Function.name.
function doSomething() {
// does something
}
console.log(doSomething.name); // "doSomething"
Note that this only works for function declarations and named function expressions. Unnamed function expressions won't work.
var getA = function getA() {
};
console.log(getA.name); // "getA"
var getB = function() { // Notice the lack of a name
};
console.log(getB.name); // ""
You can use functionVariable.name, here is an example:
x = function test() {}
console.log(x.name)
// logs "test"
Related
I have three functions. I want to write another function where I can use an argument in the form of an integer, in order to chose which one of the other functions to invoke. For example, using the argument "1" will invoke sayNum1 etc.
Or, can I write a function that with the use of an integer, invokes a specific console.log instead?
function sayNum1() {
console.log("One");
}
function sayNum2() {
console.log("Two");
}
function sayNum3() {
console.log("Three");
}
It seems like you want to create a mapping of integers to English number names. An array is a suitable data structure for this task because its members are indexed by integer values (but you could also use a plain object). Here's an example:
const numberNames = ['Zero', 'One', 'Two', 'Three' /* etc. */];
function sayNum (int) {
const name = numberNames[int];
if (typeof name === 'string') {
console.log(name);
}
else {
// There was no name defined at the requested integer index
// Do nothing — or something else instead?
console.log('No name found for that number');
}
}
numberNames[20] = "Twenty";
sayNum(1); // "One"
sayNum(3); // "Three"
sayNum(4); // "No name found for that number"
sayNum(20); // "Twenty"
sayNum(21); // "No name found for that number"
// etc...
If you're specifically wondering how to invoke other functions by using a parameter, you can follow the pattern in the example above, but store the functions themselves in the array:
function sayNum1() {
console.log("One");
}
function sayNum2() {
console.log("Two");
}
function sayNum3() {
console.log("Three");
}
const logFunctions = [];
logFunctions[1] = sayNum1;
logFunctions[2] = sayNum2;
logFunctions[3] = sayNum3;
function sayNum (num) {
const fn = logFunctions[num];
if (typeof fn === 'function') fn();
}
sayNum(1); // "One"
sayNum(2); // "Two"
sayNum(3); // "Three"
sayNum(4); // Does nothing
I hope the below code is suitable for you , if any queried let me know.
function sayNum1(){
alert("one");
}
function sayNum2(){
alert("two");
}
function sayNum3(){
alert("three");
}
function mainprogram(){
let val = document.getElementById('input').value;
if(val){
// if(!!window.["sayNum"+ val]){
window["sayNum"+ val]();
//}else{
//alert("This function is not Exist");
//}
}
}
(1|2|else)<input id=input onchange='mainprogram()'>
<p>Inputbox is just for passing arguments. you can use in your third function arguments</p>
<p>Note: uncomment the lines of commented for avoid runtime error, but code snippet not allowed those lines, you can use in your code</p>
Thank you.
so i have a piece of code where i have an array (ar=[1,2,3,4,5]) and two functions. the functions are supposed to do the exact same thing: print out something if 1 exists in the array. but function func is always returning "nope" instead of "one" but function another always return the right thing. the only difference between the two functions is function func have a switch instead of an if/else. why? in the source code there are about 12 cases so i actually need to use the switch.
var ar=[1,2,3,4,5];
function func(num){
var one=num;
switch (one) {
case one===1:
console.log("one");
break;
default:
console.log("nope");
break;
}
}
function another (num) {
if(num===2){
console.log("found two");
} else if(num===3){
console.log("found thre");
} else{
console.log("nope");
}
}
ar.forEach(func);
ar.forEach(another);
You have to use the value you want to compare to one
hence
case 1:
instead of
case one===1
here's a fiddle
https://jsfiddle.net/cunx1ono/
Easiest way. Change the switch param to true if you want to use a comparison in the case, because one===1 returns true/false. This is why you always get "nope".
var ar=[1,2,3,4,5];
function func(num){
var one=num;
switch (true) {
case one===1:
console.log("one");
break;
default:
console.log("nope");
break;
}
}
I would like to create a function "when", that will work as a normal command, or just a function, and will be able to re-evaluate its parameters.
for example:
when(k==0) {
do something;
}
or
when(k==0, function() {
do something;
});
The thing is, that k is now for example equal to 1, and this function needs to always re-evaluate k==0 to determinate if it changed to 0.
*I do not want to send k==0 as a string 'k==0'.
Is that possible? If so, how?
*This is an academic question, please don't explain why it is so very wrong to create this function.
something like this?
function when(condition, callback){ if (condition) callback() }
and call it like
var a = 0;
when(a == 0, function(){ console.log( "yeyyyy") } );
after reading the comments above
some kind of mechanism for observing when a variable's value changes
change when method to
function when(lhs, operator, rhs, callback)
{
var result = false;
switch( operator )
{
case "==": result = (lhs==rhs); break;
case "===": result = (lhs===rhs); break;
case "<": result = (lhs<rhs); break;
case ">": result = (lhs>rhs); break;
case "<=": result = (lhs<=rhs); break;
case ">=": result = (lhs>=rhs); break;
default: result = true;
}
if (result) { callback() }
else { setTimeout( function(){ when(lhs, operator, rhs, callback) }, 1000 ); }
}
What would work would be to use a lambda for both the condition and the action. Using arrow function expressions (thanks #Kyll), it's even reasonably compact.
when (() => k == 0, () => { do something; });
I'm using a modalService to store modal templates in my mainController.
Here is how I store them (from mainController)
// Store popup modal:
$ionicModal.fromTemplateUrl('app/popup/popup.html', {})
.then(function(modal) {
PopupFactory.storeModal(modal);
});
// Store addTicker modal:
$ionicModal.fromTemplateUrl('app/tickers/addTicker.html', {})
.then(function(modal) {
ModalFactory.storeModal('addTicker', modal);
});
modalFactory
This is what the storeModal function looks like:
function storeModal(type, modal) {
switch(type) {
case 'addTicker':
vm.addTicker = modal;
break;
case 'addTag':
vm.addTag = modal;
break;
}
}
^ as you can see I have to create an object for each modal my app will have.
This is what the getModal function looks like:
function getModal(type) {
switch(type) {
case 'addTicker':
return vm.addTicker;
break;
case 'addTag':
return vm.addTag;
break;
case 'anotherModal':
return vm.anotherModal;
break;
case 'yetAnotherModal':
return vm.yetAnotherModal;
break;
}
}
I feel like this code can be optimized to 1 or 2 lines...
I've tried the follow to no avail:
function getModal(type) {
return vm.+type;
}
and
function getModal(type) {
var returned = type;
return vm.returned;
}
However when I call getModal in the respective Directive Controllers, I get undefined:
function addTickerButton() {
vs.addTicker = ModalFactory.getModal('addTicker');
vs.addTicker.show('addTicker);
$rootScope.$emit("modal.add.tickers");
}
You got very close here:
function getModal(type) {
var returned = type;
return vm.returned;
}
But you are trying to access a returned attribute on vm, which doesn't exist. To retrieve an attribute using a variable, you must use bracket notation:
function getModal(type) {
return vm[type];
}
Just do
function getModal(type) {
return vm[type];
}
What you need is an object accessor with bracket notation:
vm[type] = modal
See this link for more details.
I'm using a run-time assignment of functions to account for browser differences. However for un-supported browsers, I want to return an empty function so that a JavaScript error is not thrown.
But, jslint complains about empty functions. What is the jslint happy way to do this?
Empty block.
$R.functionNull = function () {
// events not supported;
};
$R.Constructor.prototype.createEvent = (function () {
if (doc.createEvent) {
return function (type) {
var event = doc.createEvent("HTMLEvents");
event.initEvent(type, true, false);
$NS.eachKey(this, function (val) {
val.dispatchEvent(event);
});
};
}
if (doc.createEventObject) {
return function (type) {
var event = doc.createEventObject();
event.eventType = type;
$NS.eachKey(this, function (val) {
val.fireEvent('on' + type, event);
});
};
}
return $R.functionNull;
}());
You can add a body to your function and have it return undefined:
$R.functionNull = function() {
// Events not supported.
return undefined;
};
This keeps the same semantics as a "truly empty" function, and should satisfy JSLint.
Use the lambda expression:
$R.functionNull = () => void 0;
For me this works best:
emptyFunction = Function();
console.log(emptyFunction); // logs 'ƒ anonymous() {}'
console.log(emptyFunction()); // logs 'undefined'
It's so short that I wouldn't even assign it to a variable (of course you can also use a constant-like variable "EF" or so, that's even shorter and doesn't need the additioal "()" brackets). Just use "Function()" anywhere you need a truly empty function, that doesn't even have a name, not even when you assign it to a variable, and that's the small behaviour difference between my solution and Frédéric's:
// --- Frédéric ---
emptyFunction = function() {
return undefined;
}
console.log(emptyFunction.name); // logs '"emptyFunction"'
// --- me ---
emptyFunction = Function();
console.log(emptyFunction.name); // logs '""' (or '"anonymous"' in chrome, to be fair)
What about returning
return () => undefined;
instead of
return $R.functionNull;