最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Operatorin JavaScript : 5.02.0 = 5? - Stack Overflow

programmeradmin1浏览0评论

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 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.

Share Improve this question edited Apr 28, 2017 at 19:59 Michael e lately 9,4528 gold badges68 silver badges94 bronze badges asked Nov 2, 2011 at 17:46 YksinYksin 311 bronze badge 4
  • 3 As you might have seen by looking at the syntax highlighting, // .. are the markers of a ment in JavaScript. Also, if you need tips for your English, visit english.stackexchange. – Rob W Commented Nov 2, 2011 at 17:48
  • 14 This is the first time I've seen a question that is answered by its syntax highlighting. – SLaks Commented Nov 2, 2011 at 17:49
  • 1 See this question for integer division in JavaScript – Alex Turpin Commented Nov 2, 2011 at 17:54
  • 2 I think Yksin was ashamed of ing back to SO after he saw what his mistake was. @Yksin: e back, choose an answer, we all make silly mistakes – Ruan Mendes Commented Nov 2, 2011 at 18:03
Add a ment  | 

5 Answers 5

Reset to default 7

// is a ment 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);

In JavaScript, // is not an operator, it denotes a ment.

// is used for menting in JavaScript.

// starts a ment. 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 parison.

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

发布评论

评论列表(0)

  1. 暂无评论