开发者

is there a shorter way for this condition?

开发者 https://www.devze.com 2023-01-16 20:06 出处:网络
if (form.a.value !=\"\"&&form.b.value!=\"\" &&form.c.value !=\"\") is there a shorte开发者_JS百科r way for this condition?Javascript is weakly-typed so you can treat empty string as
if (form.a.value !=""&&form.b.value!="" &&form.c.value !="")

is there a shorte开发者_JS百科r way for this condition?


Javascript is weakly-typed so you can treat empty string as boolean false, so the following code should work:

if (form.a.value && form.b.value && form.c.value) {

However I don't know why would you want to change that code. Actually it's quite clear and verbose.


If you have only three fields(or less), you can leave it as is. If you have more(or unknown) number of fields to check, create an array of fields to check and do the checks in loop in separate function for better maintainability. Something like this:

if(!Empty([form.a,form.b,form.c]))
{
...
}

function Empty(elements)
{
    for(var i=0;i<elements.length;i++)
    {
        if(elements[i].value)
            return false;      
    }
}


there are lazy ways :)

if(form.a.value + form.b.value + form.c.value != "" )

if(form.a.value.length + form.b.value.length + form.c.value.length != 0 )

if(!form.a.value && !form.b.value && !form.c.value) 
0

精彩评论

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