Javascript,^(插入符号)运算符有什么作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3618340/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:27:13  来源:igfitidea点击:

Javascript, What does the ^ (caret) operator do?

javascriptmathoperators

提问by Torres

I have some javascript code:

我有一些 javascript 代码:

<script type="text/javascript">
$(document).ready(function(){
  $('#calcular').click(function() {
    var altura2 = ((($('#ddl_altura').attr("value"))/100)^2);
    var peso = $('#ddl_peso').attr("value");
    var resultado = Math.round(parseFloat(peso / altura2)*100)/100;
    if (resultado > 0) {
      $('#resultado').html(resultado);
      $('#imc').show();
    };
  });
});
</script>

What does the ^(caret) operator mean in Javascript?

什么是^(尖)运算符在Javascript中是什么意思?

回答by Gumbo

The ^operatoris the bitwise XOR operator. To square a value, use Math.pow:

^操作是按位异或运算符。要平方值,请使用Math.pow

var altura2 = Math.pow($('#ddl_altura').attr("value")/100, 2);

回答by e2-e4

^is performing exclusive OR (XOR), for instance

^正在执行异或(XOR),例如

6is 110in binary, 3is 011in binary, and

6110二进制的,3011二进制的,并且

6 ^ 3, meaning 110 XOR 011gives 101 (5).

6 ^ 3, 意思是110 XOR 011101 (5)。

  110   since 0 ^ 0 => 0
  011         0 ^ 1 => 1
  ---         1 ^ 0 => 1
  101         1 ^ 1 => 0

Math.pow(x,2) calculates x2but for square you better use x*xas Math.pow uses logarithms and you get more approximations errors. ( x2 ~ exp(2.log(x)))

Math.pow(x,2) 计算x2但对于平方你更好地使用,x*x因为 Math.pow 使用对数并且你得到更多的近似误差。( x2 ~ exp(2.log(x)))

回答by Petar Minchev

This is the bitwise XOR operator.

这是按位异或运算符。

回答by Sarfraz

The bitwise XOR operator is indicated by a caret ( ^ ) and, of course, works directly on the binary form of numbers. Bitwise XOR is different from bitwise OR in that it returns 1 only when exactly one bit has a value of 1.

按位异或运算符由插入符号 ( ^ ) 表示,当然,它直接作用于数字的二进制形式。按位异或与按位或的不同之处在于,它仅在恰好一位值为 1 时才返回 1。

Source: http://www.java-samples.com/showtutorial.php?tutorialid=820

来源:http: //www.java-samples.com/showtutorial.php?tutorialid= 820

回答by Shubham Verma

Its called bitwise XOR. Let me explain it:

它称为按位异或。让我解释一下:

You have :

你有 :

Decimal Binary   
0         0
1         01
2         10
3         11

Now we want 3^2=? then we have 11^10=?

现在我们想要3^2=?那么我们有11^10=?

11
10
---
01
---

so 11^10=0101in Decimal is 1.

所以11^10=0101十进制是1.

So we can say that 3^2=1;

所以我们可以说 3^2=1;