“|”的功能是什么? (管道)操作员? [英] What's the function of the "|" (pipe) operator?

查看:80
本文介绍了“|”的功能是什么? (管道)操作员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从另一个地方复制了这一行:

I have this line that I copied from another place:

Total += parseFloat($(this).val())|0;

运营商的功能是什么 | ?当我更改数字时,我会得到不同的结果。

What's the function of the operator |? When I change the number, I get different results.

推荐答案

| 在JavaScript中是整数按位OR运算符。在这种情况下,它会剥离 parseFloat 返回的任何小数部分。表达式 parseFloat($(this).val())将导致一个带有(可能)小数组件的数字,但是 | 0 将其转换为整数,或者 0 (这意味着它不会改变),因此总体结果是得到一个整数。

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.

所以功能上如此,它截断数字的小数部分。 -1.5 变为 -1 1.5 变为 1 。这就像 Math.floor ,但截断而不是舍入向下( Math.floor(-1.5) -2  —下一个最低整数 —而不是 -1 因为 | 0 版本给了我们。)

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;

这可以防止 $(this).val()返回或类似内容,导致 parseFloat 返回 NaN 。它使用奇怪的强大 || 运算符在这种情况下返回 0 而不是 NaN 。 (并且有一个广告,用于在您的运营商周围放置空格。)必须知道代码的上下文,以说明是否截断为整数( | )在添加到 Total 时有意义,或者他们只是在捍卫 NaN 案例。

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.

这篇关于“|”的功能是什么? (管道)操作员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆