开发者

Forcing JavaScript return false to persist through functions

开发者 https://www.devze.com 2023-04-06 22:02 出处:网络
Thanks for taking time to review this question. I\'ve been trying to fix a problem for one or two hours with no success...

Thanks for taking time to review this question. I've been trying to fix a problem for one or two hours with no success...

I have a web page that sets a JavaScript variable based on the response from a function:

grade = getScore(questionAnswer, userAnswer, questionType);

(userAnswer is the user's answer to a question and is retrieved from a textarea)

Here is getScore:

function getScore(questionAnswer, userAnswer, questionType) {

    switch(questionType) {
        case 'multiplechoice':
            return scoreMC(questionAnswer, userAnswer);
        break;

        case 'usertypesanswer':
            return scoreTA(questionAnswer, userAnswer);         
        break;

        default:
            return 0
    }   

}

The functions for scoreMC and scoreTA have been tested thoroughly and work great. The issue is that if a user's answer is not formatted correctly, scoreMC or scoreTA will return false. Otherwise it returns the values score and msg. However, instead of getting a "false" value for "grade" when I set the value of the grade variable based on the getScore function, I get "undefined". (We have no problems when the user response validates properly.)

After setting "grade", I have tried to check if any part of it is undefined:

if(typeof(grade.score) !== undef开发者_StackOverflowined)

I do not understand why, but even when I see "undefined" in my Firebug console, grade.score passes this check...

Does anyone see what I am doing wrong? Thank you very much for your assistance. I have a lot to learn about JavaScript.


if(typeof(grade.score) !== undefined)

can be

if(grade.score && grade.score !== false) // if I understand your question 

or

if(typeof(grade.score) !== "undefined")

typeof returns a string


If no return statement is used (or an empty return with no value), JavaScript returns undefined.

It is almost certain that one of your score functions (scoreMC, scoreTA, whose code you should have included in the question) does not return a value i.e.

return;

Or just reaches the end of the function code block without encountering a return.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号