为什么“a + + b”工作,但“a ++ b”不? [英] Why does "a + + b" work, but "a++b" doesn't?

查看:82
本文介绍了为什么“a + + b”工作,但“a ++ b”不?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在摆弄不同的东西,比如这个

I was fiddling around with different things, like this

var a = 1, b = 2;
alert(a + - + - + - + - + - + - + - + b); //alerts -1

我可以删除这些空格,它仍然有效。

and I could remove the spaces, and it would still work.

a+-+-+-+-+-+-+-+b

然后我试过

a + + b

它运行并计算为3,但当我删除空格时,( a ++ b )它不会运行,它有一个警告,上面写着令人困惑的加号。

It ran and evaluated to 3, but when I removed the spaces, (a++b) it wouldn't run, and it had a warning which read "Confusing plusses."

我可以理解,在

a+++++b

可以解释为以下任何一种

which could be interpreted as any of the following

(a++) + (++b)
(a++) + +(+b)
a + +(+(++b))
a + +(+(+(+b)))

这会让人感到困惑。

但是对于

a++b

据我所知,唯一有效的解释方法是

the only valid way to interpret this, as far as I can tell, is

a + +b

为什么不 a ++ b 工作?

推荐答案

Javascript解析器贪婪(它匹配每次最长有效运算符),因此从 a ++ b 获取 ++ 运算符,使得:

The Javascript parser is greedy (it matches the longest valid operator each time), so it gets the ++ operator from a++b, making:

(a++) b

无效。当您输入空格 a + + b 时,解析器会将其解释为:

which is invalid. When you put in spaces a + + b, the parser interprets it like this:

(a) + (+b)

这是有效的,可以是3 。

which is valid and works out to be three.

有关更多详细信息,请参阅有关 Maximal munch 的维基百科文章。

See this Wikipedia article on Maximal munch for more details.

这篇关于为什么“a + + b”工作,但“a ++ b”不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆