简体   繁体   中英

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.

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))

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 '/' .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM