此外:
true ? 1 : 0
有没有什么简短的技巧可以在 Javascript 中“翻译”True->1和 False->0?
True->1
False->0
我已经找过了,但是没有其他的办法
你说的“小把戏”是什么意思?
答案: 和 ~~6.6一样是 Math.floor的一个把戏
~~6.6
Math.floor
You can use ~~boolean, where boolean is (obviously) a boolean.
~~boolean
boolean
~~true // 1 ~~false // 0
...or you can use +true and +false
+true
+false
Lots of ways to do this
// implicit cast +true; // 1 +false; // 0 // bit shift by zero true >>> 0; // 1, right zerofill false >>> 0; // 0 true << 0; // 1, left false << 0; // 0 // double bitwise NOT ~~true; // 1 ~~false; // 0 // bitwise OR ZERO true | 0; // 1 false | 0; // 0 // bitwise AND ONE true & 1; // 1 false & 1; // 0 // bitwise XOR ZERO, you can negate with XOR ONE true ^ 0; // 1 false ^ 0; // 0 // even PLUS ZERO true + 0; // 1 false + 0; // 0 // and MULTIPLICATION by ONE true * 1; // 1 false * 1; // 0
You can also use division by 1, true / 1; // 1, but I'd advise avoiding division where possible.
1
true / 1; // 1
Furthermore, many of the non-unary operators have an assignment version so if you have a variable you want converted, you can do it very quickly.
You can see a comparison of the different methods with this jsperf.
Here is a more logical way Number()
Number()
Number(true) // = 1 Number(false) // = 0