JavaScript BlockStatement混乱 [英] JavaScript BlockStatement confusion

查看:151
本文介绍了JavaScript BlockStatement混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

{1 + ''} + 10 // 10
{1 + ''} + '' // 0

为什么会这样? BlockStatements返回0,为什么?

Why does this happen? Do BlockStatements return 0, and why?

推荐答案


BlockStatements是否返回0 ......?

Do BlockStatements return 0...?

不,返回其中最后一个表达式的值。您可以通过以下方式看到:

No, blocks return the value of the last expression within them. You can see this by just doing:

{1 + 8}

...在JavaScript控制台中,将显示 9

...in the JavaScript console, which will show 9.


{1 +''} + 10 // 10

{1 +''} +''// 0

为什么会发生这种情况?

{1 + ''} + 10 // 10
{1 + ''} + '' // 0
Why does this happen?

因为尽管块确实返回了一个值,但是不使用该值。 {1 +''} + 10 // 10 代码被评估为两个不同的项目:

Because although the block does return a value, that value is not used. {1 + ''} + 10 // 10 code is evaluated as two distinct items:

{1 + ''} // "1"
+10      // 10

...或者用标准缩进和分号书写:

...or writing those with standard indentation and semicolons:

{
    1 + '';
}
+10;

...你看到了第二个结果,好像第一个没有在那里。 + 没有加法运算符,它是 一元 + (类似于一元 - ,但它不会更改其操作数的符号)。 +10 当然是 10 ;和 +'' 0 因为将字符串应用于字符串会将字符串转换为数字,并且数字('') 0

...and you're seeing the result of the second one, as though the first one weren't there at all. The + there isn't the addition operator, it's the unary + (similar to the unary -, but it doesn't change the sign of its operand). +10 is, of course, 10; and +'' is 0 because applying the operator to a string converts the string to a number, and Number('') is 0.

你可以证明你看到了一元 + 而不是加法运算符:

You can prove that you're seeing the unary + rather than the addition operator by trying this:

{1 + ''} * 10

......这真的是

...which is really

{
    1 + '';
}
*10;

因语法错误而失败,因为没有一元 *

It fails with a syntax error because there is no unary *.

正如Felix在下面的评论中指出的那样,对于你的例子中的 + 是加法运算符(在你的情况下最终会连接字符串),它必须是两个表达式之间,一个块是声明,而不是表达式

As Felix kindly points out in the comments below, for the + in your example to be the addition operator (which would have ended up concatenating strings, in your case), it would have to be between two expressions, and a block is a statement, not an expression.

这篇关于JavaScript BlockStatement混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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