1

This sounds like preliminary question but I am unable to figure out a work around. I prefer not to use eval(). Below is my code

        var inputValue = 75;        
        var functionName = 'Math.Sin';          
        alert (functionName(inputValue));

My intent is to calculate the Mathematical Value of functionName(inputValue). Both functionName and inputValue are stored in strings (current setup id designed so and I cannot alter that). functionName and inputValue are variables and their content will change based on context.

Can I get a suggestion on how to calculate value?

1 Answer 1

5

You can store the actual functions to be called as key-value pairs, in an object, like this

var functions = {
    "Math.Sin"   : Math.sin,
    "Math.CoSine": Math.cos,
    "Math.Tan"   : Math.tan
};

var inputValue = 75;        
var functionName = 'Math.Sin';          
alert (functions[functionName](inputValue));
# -0.38778163540943045

If the inputValue is in degrees, then you can convert that to radians like this

function convertToRadian(degree) {
    return degree * Math.PI / 180.0;
}

inputValue = convertToRadian(inputValue);
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, this really helps! Any chance I can do this without introducing this new array/JSON? This helps but just in case there is an efficient way..
@user1998463 Its not JSON, its a JavaScript object and this is the best and the most efficient way, compared to other eval based options.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.