简体   繁体   English

一行检查属性是否存在并有条件地设置它?

[英]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. FWIW ,您的情况有点奇怪,因为您要进行后递增(和递减)操作,这会修改值,但会立即将初始值保存回变量,因此值不会更改。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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