Quantcast
Channel: How to execute a JavaScript function when I have its name as a string - Stack Overflow
Viewing all articles
Browse latest Browse all 38

Answer by SaidbakR for How to execute a JavaScript function when I have its name as a string

$
0
0

You may place your functions names in an Array object and then call the array key respective to each function to execute it, DEMO:

function captchaTest(msg){    let x = Math.floor(Math.random()*(21-1)) +1;    let y = Math.floor(Math.random()*(11-1)) +1;    let sum = function(){        return x+y;    }    let sub = function(){        if (y > x){            let m = y;            y = x;            x = m;            console.log(x,y,m,'--')        }        return x-y;    }    let mul = function(){        return x*y;    }     let OParr = [sum(), sub(), mul()];     let OP = Math.floor(Math.random()*OParr.length);          let s = OParr[OP]; //!!! HERE !!! is the call as array element    switch(OP){        case 0:            opra = '+';            break;        case 1:            opra = '━';            break;        default:            opra = '✖';    }    let msg2 = 'Answer the following question to continue:'    let p = prompt(msg+''+msg2+'\n'+'What is the result of '+x+opra+y+' ?','')    console.log(s,p,OP)    if (s == p){        alert ('Wow, Correct Answer!')        return true;    }    else{        alert('Sorry, the answer is not correct!')        return false;    }}

Viewing all articles
Browse latest Browse all 38

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>