Javascript 将布尔结果转换为数字/整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7820683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert boolean result into number/integer
提问by hd.
I have a variable that stores false
or true
, but I need 0
or 1
instead, respectively. How can I do this?
我有一个存储false
or的变量true
,但我分别需要0
or 1
。我怎样才能做到这一点?
回答by lonesomeday
Use the unary +
operator, which converts its operand into a number.
使用一元运算+
符,它将其操作数转换为数字。
+ true; // 1
+ false; // 0
Note, of course, that you should still sanitise the data on the server side, because a user can send any data to your sever, no matter what the client-side code says.
请注意,当然,您仍然应该清理服务器端的数据,因为无论客户端代码怎么说,用户都可以向您的服务器发送任何数据。
回答by Andy Rose
Javascript has a ternary operator you could use:
Javascript 有一个可以使用的三元运算符:
var i = result ? 1 : 0;
回答by kralyk
Imho the best solution is:
恕我直言,最好的解决方案是:
fooBar | 0
This is used in asm.js to force integer type.
这在 asm.js 中用于强制整数类型。
回答by René
I prefer to use the Number function. It takes an object and converts it to a number.
我更喜欢使用Number 函数。它接受一个对象并将其转换为数字。
Example:
例子:
var myFalseBool = false;
var myTrueBool = true;
var myFalseInt = Number(myFalseBool);
console.log(myFalseInt === 0);
var myTrueInt = Number(myTrueBool);
console.log(myTrueInt === 1);
You can test it in a jsFiddle.
您可以在jsFiddle 中对其进行测试。
回答by Gal Talmor
I created a JSperfcomparison of all suggested answers.
我创建了所有建议答案的JSperf比较。
TL;DR - the best option for all current browsers is:
TL;DR - 当前所有浏览器的最佳选择是:
val | 0;
.
.
Update:
更新:
It seems like these days they are all pretty identical, except that the Number()
function is the slowest, while the best being val === true ? 1 : 0;
.
现在看起来它们都非常相似,只是Number()
函数最慢,而最好的是val === true ? 1 : 0;
.
回答by Philip
The typed way to do this would be:
键入的方法是:
Number(true) // 1
Number(false) // 0
回答by tonyjcamp
I just came across this shortcut today.
我今天刚遇到这个捷径。
~~(true)
~~(真的)
~~(false)
~~(假)
People much smarter than I can explain:
比我更聪明的人无法解释:
回答by Charlie Lynch
When JavaScript is expecting a number value but receives a boolean instead it converts that boolean into a number: true and false convert into 1 and 0 respectively. So you can take advantage of this;
当 JavaScript 需要一个数字值但收到一个布尔值时,它会将该布尔值转换为一个数字:true 和 false 分别转换为 1 和 0。所以你可以利用这一点;
var t = true;
var f = false;
console.log(t*1); // t*1 === 1
console.log(f*1); // f*1 === 0
console.log(+t); // 0+t === 1 or shortened to +t === 1
console.log(+f); //0+f === 0 or shortened to +f === 0
Further reading Type Conversions Chapter 3.8 of The Definitive Guide to Javascript.
进一步阅读 JavaScript 权威指南的第 3.8 章类型转换。
回答by Nicholas R. Grant
I was just dealing with this issue in some code I was writing. My solution was to use a bitwise and.
我只是在我正在编写的一些代码中处理这个问题。我的解决方案是使用按位和。
var j = bool & 1;
A quicker way to deal with a constant problem would be to create a function. It's more readable by other people, better for understanding at the maintenance stage, and gets rid of the potential for writing something wrong.
处理持续问题的更快方法是创建一个函数。它更容易被其他人阅读,在维护阶段更好地理解,并且摆脱了写错的可能性。
function toInt( val ) {
return val & 1;
}
var j = toInt(bool);
Edit - September 10th, 2014
编辑 - 2014 年 9 月 10 日
No conversion using a ternary operator with the identical to operator is faster in Chrome for some reason. Makes no sense as to why it's faster, but I suppose it's some sort of low level optimization that makes sense somewhere along the way.
出于某种原因,在 Chrome 中使用与运算符相同的三元运算符没有转换更快。至于为什么它更快是没有意义的,但我认为这是某种低级优化,在此过程中的某个地方是有意义的。
var j = boolValue === true ? 1 : 0;
Test for yourself: http://jsperf.com/boolean-int-conversion/2
自己测试:http: //jsperf.com/boolean-int-conversion/2
In FireFox and Internet Explorer, using the version I posted is faster generally.
在 FireFox 和 Internet Explorer 中,使用我发布的版本通常会更快。
Edit - July 14th, 2017
编辑 - 2017 年 7 月 14 日
Okay, I'm not going to tell you which one you should or shouldn't use. Every freaking browser has been going up and down in how fast they can do the operation with each method. Chrome at one point actually had the bitwise & version doing better than the others, but then it suddenly was much worse. I don't know what they're doing, so I'm just going to leave it at who cares. There's rarely any reason to care about how fast an operation like this is done. Even on mobile it's a nothing operation.
好吧,我不会告诉你应该或不应该使用哪一种。每个该死的浏览器在使用每种方法执行操作的速度方面都在上下波动。Chrome 在某一时刻实际上按位 & 版本比其他版本做得更好,但后来突然变得更糟。我不知道他们在做什么,所以我将把它留给谁在乎。很少有理由关心这样的操作完成得有多快。即使在移动设备上,它也无任何操作。
Also, here's a newer method for adding a 'toInt' prototype that cannot be overwritten.
此外,这里有一种较新的方法,用于添加无法覆盖的“toInt”原型。
Object.defineProperty(Boolean.prototype, "toInt", { value: function()
{
return this & 1;
}});
回答by Gustav Barkefors
The unary +
operator will take care of this:
一元运算+
符会处理这个:
var test = true;
// +test === 1
test = false;
// +test === 0
You'll naturally want to sanity-check this on the server before storing it, so that might be a more sensible place to do this anyway, though.
在存储它之前,您自然希望在服务器上对其进行完整性检查,因此无论如何,这可能是一个更明智的地方。