Jai*_*ios 24 javascript typescript
我正在使用这本电子书作为参考学习TypeScript .我已经检查了TypeScript官方文档,但是我找不到有关枚举标志的信息.
Dav*_*ret 55
它们是一种有效存储和表示布尔值集合的方法.
例如,取这个标志枚举:
enum Traits {
None = 0,
Friendly = 1 << 0, // 0001 -- the bitshift is unnecessary, but done for consistency
Mean = 1 << 1, // 0010
Funny = 1 << 2, // 0100
Boring = 1 << 3, // 1000
All = ~(~0 << 4) // 1111
}
Run Code Online (Sandbox Code Playgroud)
而不是只能像这样表示单个值:
let traits = Traits.Mean;
Run Code Online (Sandbox Code Playgroud)
我们可以在一个变量中表示多个值:
let traits = Traits.Mean | Traits.Funny; // (0010 | 0100) === 0110
Run Code Online (Sandbox Code Playgroud)
然后单独测试它们:
if (traits & Traits.Mean) {
console.log(":(");
}
Run Code Online (Sandbox Code Playgroud)
Pat*_*ins 17
官方文档有这个例子,我将添加一些对使用枚举和标志至关重要的细节.
enum FileAccess {
None,
Read = 1 << 1,
Write = 1 << 2,
}
Run Code Online (Sandbox Code Playgroud)
在TypeScript中,您可以直接指定值 =
let x:FileAccess = FileAccess.Read;
Run Code Online (Sandbox Code Playgroud)
但这可能会覆盖以前的值.为了解决这个问题,您可以使用|=附加标志.
x |= FileAccess.Write;
Run Code Online (Sandbox Code Playgroud)
此时,变量x是Read和Write.您可以使用&符号和波形符删除值:
x &= ~FileAccess.Read;
Run Code Online (Sandbox Code Playgroud)
最后,您可以比较以查看是否将其中一个值设置为变量.接受的答案是不对的.它不应该只使用&符号,还要检查===所需的值.原因是&符号返回一个数字,而不是布尔值.
console.log(FileAccess.Write === (x & FileAccess.Write)); // Return true
console.log(FileAccess.Read === (x & FileAccess.Read)); // Return false
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11601 次 |
| 最近记录: |