简体   繁体   English

JavaScript-这些值分配(使用| =作为运算符)是什么意思?

[英]JavaScript - What does these value-assignment (using |= as an operator) mean?

Today I have seen these code-snippet: 今天,我看到了以下代码片段:

  /**
     * @param src: any variable of any type
     * @param html: output format (true|false); default = false
     * @param level: (internal, don't use)
     *
     * @return string: formatted output
     */
    function showObj(src, html, level) {
      level |= 0;

Complete script: https://codereview.stackexchange.com/questions/123283/helper-function-to-format-output-any-type-of-variable 完整的脚本: https : //codereview.stackexchange.com/questions/123283/helper-function-to-format-output-any-type-of-variable

What is the value-assignment with |= ( in "level |= 0" ) ? | =(在“级别| = 0”中)的值分配是什么?

I haven't seen it anywhere before and can't find anything about it. 我以前从没见过它,也找不到任何东西。

That( | ) is a bit wise or operator , It normally used in situations where the decimal points of a number has to be truncated. That( | )是按位运算符 ,通常用于必须将数字的小数点截断的情况。

var level = 2.444434;
level |= 0; // level = level | 0;
console.log(level) // 2

The bitwise OR assignment operator uses the binary representation of both operands, does a bitwise OR operation on them and assigns the result to the variable. 按位“或”赋值运算符使用两个操作数的二进制表示,对它们进行按位“或”运算并将结果分配给变量。

Live Demo 现场演示

 var bar = 5; bar |= 2; // 7 alert(bar) 

Source 资源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM