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

javascript - How come "minus, space, minus" evaluates to the "plus" operator? - Stack Overfl

programmeradmin1浏览0评论
node -e 'console.log(- -1)' // prints 1 which makes sense

However:

node -e 'console.log(1 - - 1)' // prints 2 which does not make sense to me

integer - - integer magically converts "minus, space, minus" to the "plus" operator. Why?

Update: It seems I wasn't clear enough. The question is not why double negative in mathematics will always evaluate to a positive but how this magically evaluates to the + operator; these are two different scenarios - making a negative number positive is one thing, invoking implicitly the + is another thing.

node -e 'console.log(- -1)' // prints 1 which makes sense

However:

node -e 'console.log(1 - - 1)' // prints 2 which does not make sense to me

integer - - integer magically converts "minus, space, minus" to the "plus" operator. Why?

Update: It seems I wasn't clear enough. The question is not why double negative in mathematics will always evaluate to a positive but how this magically evaluates to the + operator; these are two different scenarios - making a negative number positive is one thing, invoking implicitly the + is another thing.

Share Improve this question edited Jul 23, 2015 at 22:02 Vidul asked Jul 23, 2015 at 20:51 VidulVidul 10.6k2 gold badges19 silver badges20 bronze badges 2
  • 2 mathsisfun./positive-negative-integers.html – Thom-x Commented Jul 23, 2015 at 20:53
  • 3 Well, you are subtracting a negative number. – John Weisz Commented Jul 23, 2015 at 20:54
Add a ment  | 

5 Answers 5

Reset to default 10

Makes perfect sense, a double negative in mathematics will always evaluate to a positive

One of your - characters is a unary minus, or a negative sign. That makes one of your literals a "negative one". The other one is a subtraction.

1 - - 1

is the same as:

1 - (-1)

While

- - 1

is the same as

0 - (-1)

It is interpreting 1 - - 1 as 1 - -1 which equals 2.

If you think about it, "- -1" equals to "+1", so "1 - - 1" equals to "1 + 1" which equals two.

In math -- = +. If I take 1 - (-1) I get 2. Subtracting a negative number is the same as adding the number...

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论