What's the function of the "
This question already has an answer here:
The |
in JavaScript is an integer bitwise OR operator. In that context, it strips off any fractional portion returned by parseFloat
. The expression parseFloat($(this).val())
will result in a number with (potentially) a fractional component, but then |0
will convert it to an integer number, OR it with 0
(which means it won't change), and so the overall result is to get a whole number.
So functionally, it truncates the fractional portion off the number. -1.5
becomes -1
, and 1.5
becomes 1
. This is like Math.floor
, but truncating rather than rounding "down" ( Math.floor(-1.5)
is -2
— the next lowest whole number — rather than -1
as the |0
version gives us).
So perhaps that's why it was used, to chop off (rather than "floor") the fractional portion of the number.
Alternately, it could be a typo. The author of that code might have meant to write this (note ||
rather than |
):
Total += parseFloat($(this).val()) || 0;
That defends against the possibility that $(this).val()
returns ""
or similar, resulting in parseFloat
returning NaN
. It uses the curiously-powerful ||
operator to return 0
rather than NaN
in that case. (And there's an advertisement for putting spaces around your operators.) Would have to know the context of the code to say whether truncating to a whole number ( |
) makes sense when adding to Total
, or if they were just defending the NaN
case.
The |
operator in javascript is the bitwise or operator
This operator treats the operands as 32 bit integers and for every bit returns 1 if either is 1 and 0 otherwise.
链接地址: http://www.djcxy.com/p/77430.html上一篇: 堆栈溢出
下一篇: 什么是“