Is there a //
operator in JavaScript?
Because in Python we have:
5 // 2.0 # => 2.0
5 / 2.0 # => 2.5
So I tried in JavaScript:
5.0//2.0
and I got 5
? What's going on there?
I read that there is no such a thing as a //
operator in JavaScript. In this case, why didn't I get an exception or, better, an error from the lexer?
I used this line:
document.write(eval("5.0//2.0"));
In Firefox 3.6.23.
//
is a comment in javascript.
Try:
5 / 2; //yields 2.5
Math.floor(5/2); //yields 2
Also do not use eval.
Just do document.write(5/2);
在JavaScript中, //
不是运算符,它表示注释。
//用于在JavaScript中进行评论。
//
starts a comment. To do integer division, first perform a regular division using /
and then round it. This can be done with &-1
, ^0
, |0
or ~~
, in order from fast to slow as measured on my laptop. There is a measurable difference between the first three but it's small. The last one is really slow in comparison.
Putting it all together, 5/2&-1
will yield 2. It rounds towards zero.
You want to use ~~ 5/2 to get 2. NO need to download math. library
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.