赋值返回的值 [英] Value returned by the assignment

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

问题描述

为什么常规赋值语句(例如,x = 5)返回分配的值(在本例中为5),而赋值与变量声明(var x = 5) 返回 undefined?

Why does the regular assignment statement (say, x = 5) return the value assigned (5 in this case), while the assignment combined with a variable declaration (var x = 5) returns undefined?

我通过在 Chrome 浏览器的 Javascript 控制台中执行这些语句获得了返回值:

I got the return values by executing these statements in the Chrome browser's Javascript console:

> var x = 5;
undefined
> y = 5;
5

推荐答案

这就是语言的设计方式.它与大多数语言一致.

That's the way the language was designed. It is consistent with most languages.

让变量声明返回除 undefined 之外的任何内容是没有意义的,因为您永远不能在表达式上下文中使用 var 关键字.

Having a variable declaration return anything other than undefined is meaningless, because you can't ever use the var keyword in an expression context.

赋值是一个 expression 而不是 statement 当你想一次将多个变量设置为相同的值时很有用:

Having assignment be an expression not a statement is useful when you want to set many variable to the same value at once:

x = y = z = 2;

也可以这样使用:

x = 2*(y = z); // Set y = z, and x = 2*z

然而,这不是最易读的代码,最好写成:

However that is not the most readable code and it would probably be better written as:

y = z;
x = 2*z;

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

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