【问题标题】:Javascript mystery commandJavascript神秘命令
【发布时间】:2014-11-19 14:13:05
【问题描述】:

我是 JavaScript 新手,必须弄清楚程序的功能。其中两个整数与这个不等式进行比较:

【问题讨论】:

  • 欢迎来到 SO。请在上下文中发布代码。
  • <<= 不是比较,而是移位,结果存储在左侧变量中。它可能在内部,如果像 if (a <<= 3) ... 一样,但只需检查 a << 3 的结果是否不为零并将结果存储回 a 以供以后使用。

标签: javascript command


【解决方案1】:

它通过将左值左移右边的值来更新左值。

var a = 1;
a <<= 2; // leftshift it by 2 bits,
         // in effect multiplying it by 4, making it 4

a  += 1; // a more common (familiar?) example of this kind of operator
         // add 1, making it 5

【讨论】:

    【解决方案2】:

    这是带有赋值的 javascript 按位左移。 javascript位运算符用法示例:

    // helper function for displaing results
    var output = function(operator, result) {
        console.log(operator + " " + result);
    }
    
    // variables
    var a = 5;
    var b = 13;
    
    // a | b - OR
    // if in any of the given numbers corresponding bit 
    // is '1', then the result is '1'
    output('or', a|b); // 13
    
    // a & b - AND
    // if in both of the given numbers corresponding bit 
    // is '1', then the result is '1'
    output('and', a&b); // 5 
    
    // a ^ b - XOR
    // if in one of the given numbers (not both) 
    // corresponding bit is '1', then the result is '1'
    output('xor', a^b); // 8
    
    // ~a - NOT
    // inverts all the bits
    output('not', ~a); // -6
    
    // a >> b - RIGHT SHIFT
    // shift binary representation of 'a' for 'b' 
    // bits to the right, discarding bits shifted off
    output('rs', a>>b); // 0
    
    // a << b - LEFT SHIFT
    // shift binary representation of 'a' for 'b' 
    // bits to the right, shifting in zeros from the right
    output('ls', a<<b); // 40960
    
    // a >>> b - ZERO FILLED RIGHT SHIFT
    // shift binary representation of 'a' for 'b' 
    // bits to the right, discarding bits shifted off, 
    // and shifting in zeros from the left.
    output('zfrs', a>>>b); // 0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 2018-11-28
      • 2013-03-11
      相关资源
      最近更新 更多