简体   繁体   中英

One line check if property exists and conditionally set it?

I would like to rewrite this code in one line, if at all possible:

//Obj is my mystery object - I don't know whether or not property x exists, but if it does, I want to set it!

if (Obj.x) {
   Obj.x = (Obj.x > 0) ? Obj.x++ : Obj.x--;
}

One possible way:

Obj.x && (Obj.x = Obj.x > 0 ? Obj.x++ : Obj.x--);

Or less ideal:

Obj.x = Obj.x ? Obj.x > 0 ? Obj.x++ : Obj.x-- : Obj.x;

FWIW , your case is a bit strange, as you do the post increment (and decrement), which amends the value, but immediately save the initial value back to the variable, so the value doesn't change. You'd better either not save the value back:

Obj.x && (Obj.x > 0 ? Obj.x++ : Obj.x--);

or do it differently:

Obj.x && (Obj.x = Obj.x > 0 ? Obj.x + 1 : Obj.x - 1);

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