Returning function value from array using random s

2019-08-18 02:19发布

问题:

Been running into some problems with returning the computed value of a function that is inside an array. and would appreciate any help in solutions as well as advice about more elegant ways of approaching this type of problem (i.e. a more logical way to have solved this)

I'm trying to create a program that generates two random digits and a random operator to apply to said digits.

var num1 = Math.floor(Math.random() * 20 + 1);
console.log(num1);
var num2 = Math.floor(Math.random() * 1000 + 21);
console.log(num2);

I originally set my random operator this way:

var ops = ["+", "-", "*", "/"] 

I tried to use a Math.random function to select a random index number for the ops array, but was getting all kinds of errors, so I started searching and found some helpful advice here: How to use Javascript to ask the user random math questions?, but couldn't figure out a way to retrieve a random value from the object,(cf. Access non-numeric Object properties by index?) so I changed back to using an array of 4 functions, each of which has a return value that computes the random numbers (num1 and num2) based on the random operator.

I've gotten everything to work (i.e. have tested my random number functions are working, and even see that my newOp variable is returning a different function from the ops array each time), but here's what I can't get the program to do: return the computed value of the function. When I

alert(newOp)

I want it to alert the function's value instead of the function itself. (e.g. alert -> 20 instead of what I'm currently getting: --> function a(){return (num1 + num2)}

Here's my code. All advice and insight welcome! Just trying to learn.

var num1 = Math.floor(Math.random() * 20 + 1);
console.log(num1);
var num2 = Math.floor(Math.random() * 1000 + 21);
console.log(num2);
var ops = [
    function a(){return (num1 + num2)}, 
    function b(){return (num1 - num2)}, 
    function c(){return (num1 * num2)},
    function d(){return (num1 / num2)}];

var problem = function () {
    var random = Math.floor(Math.random()* 4 + 0);
    var newOp = ops[random];
    alert(newOp);
};
problem();

回答1:

I think you just need to change it to:

alert(newOp());

Your array contains references to the functions, but you're not invoking them.



回答2:

I think you are just missing the actual invocation.

Change alert(newOp); to alert(newOp());