开发者

Is there a way to simplify this javascript if-statement?

not an expert on js but this if-statement still tickles me 开发者_如何学运维because I suspect it can be written in a way more clever fashion:

if(event.value == "/")
{
    event.value = "/home";
}

Suggestions?


You could omit the braces:

if(event.value == "/") event.value = "/home";

Or a conditional:

event.value = event.value == "/" ? "/home" : event.value;

...but I'm not sure either of those is really "better", and a with statement you should just stay away from.


if(event.value == "/"){
   event.value += "home";
}


event.value = (event.value == "/") ? "/home" : event.value;

would be about the only other practical option. The if() version is far more readable in this case.


I don't think there's a better way. You could omit the braces if your coding style guide allows you to, but it won't semantically make a difference. The shorter event.value = (event.value == '/')?'/home':event.value; is not so good, because it makes a useless assignment when the value differs from '/'.


There isn't much more you can do with it really, other than Nick's suggestions, but here's another way to throw into the mix:

event.value += (event.value == "/") ? "home" : "";

Another, just for fun:

event.value = ((function(v){ return v=="/" ? v+'home' : v }(event.value))


You can put it into function to make it look better.

function GetValue(s1, s2, s3) {
   return s1 == s2 ? s3 : s1;
}

...

event.value = GetValue(event.value, "/", "/home");

IMO it's useful only if you need it more than once.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜