# 是否有更好的书写方式v =（v == 0？1：0）; [关闭]

2020/09/26 04:47 · javascript ·  · 0评论

``````v = (v == 0 ? 1 : 0);
``````

``````v = 1 - v;
``````

``````v ^= 1;
``````

### 编辑：

``````v = (v ? 0 : 1);
``````

``````v = !v;
``````

``````v = +!v; /* Boolean invert v then cast back to a Number */
``````

`v = (v + 1) % 2`如果你通过更多的值需要周期只是改变`2``(n + 1)`假设您需要循环0,1,2就可以了`v = (v + 1) % 3`

`v = inv(v)`

``````v = v ? 0 : 1;
``````

`v = 1 - v`，或`v ^= 1``v= +!v`这样的行都可以完成工作，但是它们构成了我所说的hack。这些不是漂亮的代码行，而是可以达到预期效果的廉价技巧。`1 - v`不传达“在0和1之间切换值”。这使您的代码表达能力降低，并引入了一个地方（尽管很小），另一个开发人员将不得不解析您的代码。

``````v = dirac_delta(0,v)
``````

``````v = characteristic_function({0},v)
``````

χ （X）= 1如果X∈Aχ （X）= 0，如果X∉甲

X ˚Fdμ=Σ X∈X F（X）

X δ 一个 dμ=Σ 的x∈X δ 一个（X）=δ 一个（A）= 1。

1. 单例集的特征函数，
2. 增量功能
3. Kronecker增量功能。

``````v = Math.abs(--v);
``````

``````    0,1 -> v = 1 - v
1,2 -> v = 3 - v
4,5 -> v = 9 - v
``````

``````v = !v;
``````
``````v = v == 0 ? 1 : 0;
``````

## 解决方案清单

• `v = 1*!v`
• `v = +!v`
• `v = ~~!v`

• `v = 1-v`

## 解决方案1

``````v = 1*!v
``````

• `-123`将转换为整数`0`
• `-10`将转换为整数`0`
• `-1`将转换为整数`0`
• `0`将转换为整数`1`
• `1`将转换为整数`0`
• `2`将转换为整数`0`
• `60`将转换为整数`0`

## 解决方案2

``````v = +!v
``````

## 解决方案3

``````v = ~~!v
``````

1. 使用功能进行切换
2. 在此函数内使用更易读的实现

``````function inv(i) {
if (i == 0) {
return 1
} else {
return 0;
}
}
``````

``````v = inv(v);
``````

1. 没有代码重复
2. 如果将来您或任何人再次阅读此书，您将在最短的时间内理解您的代码。

``````if (v === 0)
{
v = 1;
}
else
{
v = 0;
}
``````

``````v = !v;
``````

``````v = Number(v == 0);
``````

``````public class Status
{
public Status(int value)
{
_actualValue = value;
}
public Status(Status status)
{
_actualValue = status._actualValue == 0 ? 1 : 0;
}

//some equals method to compare two Status objects
}

var status = new Status(0);

Status = new Status(status);
``````

``````v = ~(v|-v) >>> 31;
``````

``````v = [1, 0][v];
``````

``````v = [2, 0, 1][v]; // 0 2 1 0 ...
v = [1, 2, 0][v]; // 0 1 2 0 ...
v = [1, 2, 3, 4, 5, 0][v]; // 0 1 2 3 4 5 ...
v = [5, 0, 1, 2, 3, 4][v]; // 0 5 4 3 2 1 0 ...
``````

``````v = {0: 1, 1: 0}[v];
``````

``````v = {777: 'seven', 'seven': 777}[v];
``````

``````v = { undefined: someValue }[v]; // undefined someValue undefined someValue undefined ...
``````

``````v = +!v;
``````

`v=++v%2`

（在C语言中，这很简单`++v%=2`

ps。是的，我知道这是双重赋值，但这只是C方法的原始重写（按原样工作，因为JS预增量运算符未返回左值）。

``````v = 2+~v;
``````

`v`等于任何值的另一种创造性的实现方式将始终返回`0``1`

``````v = !!v^1;
``````

``````v=!v;
``````

v =数字（！v）

`v = v == 0`足够了。

``````var v = 0;
alert("if v  is 0 output: " + (v == 0));

setTimeout(function() {
v = 1;
alert("if v  is 1 Output: " + (v == 0));
}, 1000);``````

JSFiddle：https：//jsfiddle.net/vikash2402/83zf2zz0/