Javascript:语句和表达式之间的区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12703214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:04:25  来源:igfitidea点击:

Javascript: difference between a statement and an expression?

javascriptexpressionterminologysemantics

提问by wwaawaw

I asked thisquestion earlier, and after thinking about the topic some more, I began to wonder where the seemingly fuzzy boundary between the meanings of the terms "statement" and "expression" lies. Are all statements also expressions? Where do the return values in a REPL console come from? They don't always seem to make any intuitive sense. Of course if you type 1+1, you'll get 2, but other times it isn't as obvious what the logic is.

之前问过这个问题,仔细想了想,我开始怀疑“statement”和“expression”这两个词的含义之间看似模糊的界限在哪里。所有的语句都是表达式吗?REPL 控制台中的返回值从何而来?它们似乎并不总是具有任何直觉意义。当然,如果你输入1+1,你会得到2,但其他时候它的逻辑并不那么明显。

Given that anything typed into REPL produces somevalue, does it mean that it can be used in JS source code as both an expression and a standalone statement?

鉴于输入到 REPL 中的任何内容都会产生一些值,这是否意味着它可以在 JS 源代码中用作表达式和独立语句?

can string of code that could be used for _X_in the following snippet also be used for _Y_and vice versa? if(_X_) _Y_

可以_X_在以下代码段中使用的代码字符串也可以用于,_Y_反之亦然吗?if(_X_) _Y_

采纳答案by ZER0

Are all statements also expressions?

所有的语句都是表达式吗?

“Wherever JavaScript expects a statement, you can also write an expression. Such a statement is called an expression statement. The reverse does not hold: you cannot write a statement where JavaScript expects an expression. For example, an if statement cannot become the argument of a function.”

“在 JavaScript 需要语句的地方,你也可以写一个表达式。这样的语句称为表达式语句。反过来不成立:您不能在 JavaScript 需要表达式的地方编写语句。例如,if 语句不能成为函数的参数。”

This is comes from a recent post by Axel Rauschmayer about this topic: Expressions versus statements in JavaScript

这是来自 Axel Rauschmayer 最近关于这个主题的帖子: JavaScript 中的表达式与语句

Hope it helps.

希望能帮助到你。

回答by Marcus Junius Brutus

According to MDN:

根据MDN

An expression is any valid unit of code that resolves to a value.

表达式是解析为值的任何有效代码单元。

As such, anything that can be used as an rvalue is an expression.

因此,任何可以用作右值的东西都是一个表达式。

The criterion is notwhether side effects exist. Expressions can definitely have side effects. E.g. a=2is an expression as it has a value (2) and also assigns a value to a variable. Which is why you can do things like:

标准不是副作用是否存在。表达式肯定会产生副作用。ega=2是一个表达式,因为它有一个值 (2) 并且还给一个变量赋值。这就是为什么您可以执行以下操作:

let a;
let b = 1 + (a = 2); // a is now 2 and b is 3

It is possible for the same (textual) block of code to be considered both an expression anda statement depending on the context. E.g. the text snippet function f(){}is an expression on line 1 and a statement in line 2 in the below code:

根据上下文,相同的(文本)代码块可能被视为表达式语句。例如,文本片段function f(){}是下面代码中第 1 行的表达式和第 2 行的语句:

let g = function f() {};
function f() {};

So whether something is an expression or a statement cannot (in the general case) be determined by looking at a textual piece of code out of context; rather it is a property of a node in a syntax tree and can be decided only after the code is (mentally or actually) parsed.

因此,不能(在一般情况下)通过脱离上下文查看一段文本代码来确定某事物是表达式还是语句;相反,它是语法树中节点的属性,只有在(精神上或实际上)解析代码后才能决定。

Also, and perhaps more importantly, function statements (a.k.a function declarations) inside a function fform part of the execution context that gets created when function fis invoked. However, function expressions do notform part of that execution context.

此外,也许更重要的是,函数内的函数语句(又名函数声明)f构成了f调用函数时创建的执行上下文的一部分。但是,函数表达式构成该执行上下文的一部分。

One often quoted effect of that is that function declarations get "hoisted" whereas function expressions do not.

一个经常引用的效果是函数声明被“提升”而函数表达式不会。

A more subtle effect can also be experimentally observed in deep recursions given that function statements take up space in the execution context whereas function expressions do not. E.g. the below code uses infinite recursion of a function f. Function fin the first case includes a function expression inside it, in the second case it includes the equivalent function declaration:

考虑到函数语句在执行上下文中占用空间而函数表达式不占用空间,在深度递归中也可以通过实验观察到更微妙的效果。例如,下面的代码使用函数的无限递归ff第一种情况下的函数在其中包含一个函数表达式,在第二种情况下它包括等效的函数声明:

// Function Expression
{
    let i = 0;
    try {

        function f () {
            i++;
            (function g() {})(); // this is an expression
            f();
        }

        f();

    } catch (err) {
        console.log(`Function Expressions case: depth of ${i} reached. Error: ${err.name}`);
    }
}
// Function Declaration
{
    let i = 0;
    try {
        function f () {
            i++;
            function g() {}; // this is a statement
            g();
            f();
        }

        f();

    } catch (err) {
        console.log(`Functions Declarations case: depth of ${i} reached. Error: ${err.name}`);
    }
}

On my machine I consistently get the following (in node.js):

在我的机器上,我始终得到以下信息(在 node.js 中):

Function Expressions case: depth of 17687 reached. Error: RangeError
Functions Declarations case: depth of 15476 reached. Error: RangeError

… which is consistent with the fact that Function Declarations increase the amount of space necessary to hold an execution context and thus eat up stack space a little faster and so slightly decrease the maximum recursion depth.

……这与函数声明增加了保存执行上下文所需的空间量并因此更快地消耗堆栈空间并因此略微降低​​最大递归深度的事实一致。

回答by Praveen

Expression produces or evaluates some value.

表达式产生或评估一些值。

Examples of expressions: new Date()produces new Date object without any side effect. [1,2,3]produces a new array without any side effect. 5+6produces a new value 11.It just produces new value without any side effect.

表达式示例: new Date()生成新的 Date 对象,没有任何副作用。 [1,2,3]产生一个没有任何副作用的新数组。 5+6产生一个新值 11.它只是产生新值,没有任何副作用。

Statement produces some behavior or does something and it has some side effect also. Based on the side effect, statements can be categorized.

语句产生一些行为或做一些事情,它也有一些副作用。根据副作用,可以对语句进行分类。

x=5;is a statement and here side effect is assignment or change in x.

x=5;是一个语句,这里的副作用是 x 中的赋值或更改。

setTimeout()- start of timer is the side effect.

setTimeout()- 计时器的启动是副作用。

Statements are generally separated by semicolon.

语句通常用分号分隔。

Expression statement are the expression that has some side effect or simply "expression with side effect".

表达式语句是具有某些副作用的表达式或简称为“具有副作用的表达式”。

Examples of expression statement:

表达式语句示例:

x+=6;is the complex expression(group of primary expressions) is doing assignment that is a side effect, so called expression statement.

x+=6;是复杂表达式(主要表达式组)正在执行赋值,这是一种副作用,因此称为表达式语句。

delete a[2];

回答by U-ways

At its simplest terms, expressionsare evaluated to produce a value. On the other hand, statementsare executed to make something happen.

用最简单的术语来说,表达式被求值以产生一个值。另一方面,执行语句是为了使某些事情发生

回答by Mo Ali

Expression: a unit of code that resolves to a value, as instance, literals& operators. Examples for expressions:

表达式:解析为值的代码单元,如实例、文字运算符。表达式示例:

> 3
> 1 + 2
> "expression"
> fn()
> []
> {}


Statement: a unit of code representing one instruction or more, usually starts with a language reserved keyword and ends, explicitlyor implicitly, with a statement terminator. Examples of statements:


语句:表示一条或多条指令的代码单元,通常以语言保留关键字开头,并以语句终止符显式隐式结束。语句示例:

> 3;
> let x = 3;
> if () {}
> for () {}
> while () {}

回答by Eldiyar Talantbek

All programs in JavaScript are made of statements and they end with semicolons, except block statements which is used to group zero or more statements. Statementsare just perform some actions but do not produce any value or output whereas expressionsreturn some value. When interpreter sees an expression it retrieves its value and replaces expression with new value. Statements are used to manipulate those expressions. You can check whether it's an expresion or a statement here : JavaScript Parser

JavaScript 中的所有程序都由语句组成,它们以分号结尾,除了用于组合零个或多个语句的块语句。语句只是执行一些操作,但不产生任何值或输出,而表达式返回一些值。当解释器看到一个表达式时,它会检索它的值并用新值替换表达式。语句用于操作这些表达式。您可以在此处检查它是表达式还是语句:JavaScript Parser

回答by SherylHohman

I highly recommend reading Dr. Axel Rauschmayer's comprehensive blog post
Expressions versus statements in JavaScript
as mentioned in @ZER0's accepted answer above.

我强烈建议阅读 Axel Rauschmayer 博士的综合博客文章
表达式与 JavaScript
中的语句,如上面@ZER0 接受的答案中所述。

But my favorite memory shortcut is:

但我最喜欢的记忆快捷方式是:

Expression:
ecan be set Equal to an Expression
..orExpressedby printing it.
Statement:
..anything else.

表达式:
e可以设置EExpression
.. 或Expressed通过打印它。
声明:
..其他。



The following is modified from
Anders Kaseorg's Quora answer.

以下内容是从
Anders Kaseorg 的 Quora 回答中修改而来

A statement is a complete line of code that performs some action.

语句是执行某些操作的完整代码行。

Every Expression can be used as a statement
(whose effect is to evaluate the expression, andignore the resulting value).

Every Expression 可以用作语句
(其作用是对表达式求,并忽略结果值)

But an Expression is any section of the code that evaluates to a value.

但是Expression 是代码的任何部分,它e评估为 value e

Expressions can be combined “horizontally” into larger expressions using operators.
Ehas a horizontally flat top

表达式可以使用运算符“横向”组合成更大的表达式。
E有一个水平平坦的顶部

Most statements cannot be used as expressions.

大多数语句不能用作表达式。

Statements can only be combined “vertically” by writing one after another, or with block constructs.
Sruns vertically in comparison.

语句只能通过一个接一个地编写或使用块结构来“垂直”组合。
S相比之下,垂直运行。



From Quora Post by Ryan Lam:

来自 Ryan Lam 的 Quora Post:

Here's a general rule of thumb: If you can print it, or assign it to a variable, it's an expression. If you can't, it's a statement.

这是一个一般的经验法则:如果你可以打印它,或者将它分配给一个变量,它就是一个表达式。如果你不能,这是一个声明。

Here are some examples of expressions:

以下是一些表达式示例:

2 + 2
3 * 7
1 + 2 + 3 * (8 ** 9) - sqrt(4.0)
min(2, 22)
max(3, 94)
round(81.5)
"foo"
"bar"
"foo" + "bar"
None
True
False
2
3
4.0

All of the above can be printed or assigned to a variable.

以上所有内容都可以打印或分配给变量。

Here are some examples of statements:

以下是一些声明示例:

if CONDITION:
elif CONDITION:
else:
for VARIABLE in SEQUENCE:
while CONDITION:
try:
except EXCEPTION as e:
class MYCLASS:
def MYFUNCTION():
return SOMETHING
raise SOMETHING
with SOMETHING:

None of the above constructs can be assigned to a variable. They are syntactic elements that serve a purpose, but do not themselves have any intrinsic “value”. In other words, these constructs don't “evaluate” to anything. Trying to do any of the following, for example, would be absurd, and simply wouldn't work:

上述构造都不能分配给变量。它们是服务于某种目的的句法元素,但本身没有任何内在的“价值”。换句话说,这些结构不“评估”任何东西。例如,尝试执行以下任何操作都是荒谬的,而且根本行不通:

x = if CONDITION:
y = while CONDITION:
z = return 42
foo = for i in range(10):

回答by Premraj

We have the following two types of expressions:

我们有以下两种类型的表达式:

1. Boolean expressionis uses to execute block of statements. enter image description here

1. 布尔表达式用于执行语句块。 在此处输入图片说明

2. Arithmetic expressionis uses for variable assignments, which acts as a statementstoo.

2. 算术表达式用于变量赋值,它也充当语句

For example: number = number + 1;

例如: number = number + 1;

回答by Ershad Qaderi

A fragment of code that produces a value is called an expression. Every value that is written literally (such as 22 or "psychoanalysis") is an expression. An expression between parentheses is also an expression, as is a binary operator applied to two expressions or a unary operator applied to one.

产生值的代码片段称为表达式。每个字面上写的值(例如 22 或“心理分析”)都是一个表达式。括号之间的表达式也是表达式,就像应用于两个表达式的二元运算符或应用于一个表达式的一元运算符一样。

An expression corresponds to a sentence fragment in human language, a JavaScript statement corresponds to a full sentence. A program is a list of statements.

一个表达式对应人类语言中的一个句子片段,一个 JavaScript 语句对应一个完整的句子。程序是一个语句列表。

The simplest kind of statement is an expression with a semicolon after it. This is a program:

最简单的语句是后面有一个分号的表达式。这是一个程序:

1; !false; It is a useless program, though. An expression can be content to just produce a value, which can then be used by the enclosing code. A statement stands on its own, so it amounts to something only if it affects the world.

1; !错误的; 不过,这是一个无用的程序。表达式可以满足只产生一个值,然后可以由封闭代码使用。一个陈述是独立存在的,所以只有当它影响世界时它才有意义。

Statement could have side effects.

声明可能有副作用。

https://eloquentjavascript.net/02_program_structure.html

https://eloquentjavascript.net/02_program_structure.html