Home > front end >  Write a function to invoke other function with an argument in form of an integer
Write a function to invoke other function with an argument in form of an integer

Time:10-31

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");
}

CodePudding user response:

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

CodePudding user response:

I hope the below code is suitable for you , if any queried let me know.

function sayNum1(){
  alert("one");
}

function sayNum2(){
  alert("two");
}

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.

  • Related