^ (插入符号)在 JavaScript 中的作用是什么?

我有一些 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>

在 JavaScript 中,^(插入符号)是什么意思?

67416 次浏览

This is the bitwise XOR operator.

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

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

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.

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

^ is performing exclusive OR (XOR), for instance

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

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

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

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

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=?

11
10
---
01
---

so 11^10=01 01 in Decimal is 1.

So we can say that 3^2=1;