开发者

JSLINT warning about style or error about Conditional Expression

I'm trying to fix what JSLINT is warning about two things tha I don't know how to fix. Which line should be replaced with what code? I have pasted the code in question and the warnings about them below. Thanks very much in advance for your suggestion / answer.

JSLINT says:

Problem at line 137: Expected a conditional expression and instead saw an assignment.

while(elem = document.getElementById("optionsDiv"+g))

Problem at line 1开发者_开发技巧40: Expected '{' and instead saw 'return'.

return g;


function isAnyOptionVisible()
{
    var g=0;
    while(elem = document.getElementById("optionsDiv"+g))
    {
        if(elem.className==="optionsDivVisible")
            return g;
        g++;
    }
    return -1;
}


There is nothing wrong with the conditional, except that elem may be a global if it isn't declared in an outer scope. If it's not declared, do so before hand:

var elem, g=0;    

If you want to make JSLint happy, you can add an explicit comparison to null:

while((elem = document.getElementById("optionsDiv"+g)) !== null)

I don't see anything about "Expected {". However, putting the g++ on the same line as the brace is odd style.

Remember that JSlint is partly about Crockford's personal preferences, which you don't always have to agree with.

EDIT: Okay, the second error is because JSLint wants you to put the return in braces, e.g.:

    if(elem.className==="optionsDivVisible")
    {
        return g;
    }
    g++;

This is also the style I prefer to code in. I do find that it avoids certain errors. However, this is again subjective. The obvious tradeoff is that it adds two lines.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜