[英]Why assignments don't return undefined?
As you may know, JavaScript returns undefined
for assignments, eg var a = 0;
如您所知,JavaScript返回
undefined
分配的赋值,例如var a = 0;
. 。 However, TypeScript is not consistent with that fact, and seems to return the assigned value (
0
) – yet I could not find any information about this online. 但是,TypeScript与该事实并不一致,并且似乎返回分配的值(
0
)–但是我无法在线找到有关此信息。
As an example, see this code snippet. 作为示例,请参见以下代码片段。
function f(): void { let l: number = 1; return (l = 2); // f() returns 2 } alert(f());
I would like to learn the reasons behind this decision, and to hear opinions about it. 我想了解这项决定背后的原因,并听听对此的看法。
Your code snippet contains return (l = 2)
, an assignment , not return (var l = 2)
(which is of course not valid code), the former will return 2
in JavaScript, TypeScript, or indeed C or Java. 您的代码段包含
return (l = 2)
, 一个赋值 ,而不是return (var l = 2)
(这当然不是有效的代码),前者将在JavaScript,TypeScript或C或Java中返回2
。
A variable declaration var l = 2
is a statement, however only expressions have values. 变量声明
var l = 2
是一条语句,但是仅表达式具有值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.