0

I have created this object:

var resultStats = {
    possibleResults: 10,
    validResults: 5,
};

What would I write so that writingresultsStats["calculateSuccessRate()"] (or similar) will calculate Math.round(100*this.validResults/this.possibleResults); and return the answer of 50.

3 Answers 3

3
var resultStats = {
    possibleResults: 10.0,
    validResults: 5.0,
    calculateSuccessRate: function(){
        return Math.round(100 * this.validResults/this.possibleResults);
    }
};

The function could then be called using:

resultStats["calculateSuccessRate"]();

Or:

resultStats.calculateSuccessRate();
Sign up to request clarification or add additional context in comments.

2 Comments

(N.B. If you don't need to access the property dynamically, the bottom method is preferred.)
Thanks! But why is the bottom method preferred?
1
var resultStats = {
    calculateSuccessRate : function() {
       return Math.round(100 * (this.possibleResults / this.validResults))
    },
    possibleResults: 10,
    validResults: 5
};

Comments

0

You could a calculateSuccessRate function to the resultStats object.

var resultsStats = {
    possibleResults: 10,
    validResults: 5,
    calculateSuccessRate: function(){
        return Math.round(100*this.validResults/this.possibleResults);
    }
};

Then you can call it like:

resultsStats.calculateSuccessRate();

OR (you were close):

resultsStats["calculateSuccessRate"]()

Comments

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.