Javascript三元运算符和赋值 [英] Javascript ternary operator and assignment

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

问题描述

这个简单的JavaScript赋值语句会得到意想不到的结果:

I get unexpected result for this simple JavaScript assignment statement:

var t = 1 == 1 ? 1 : 0;
undefined

我原本希望将1分配给v。如果你做了同样的结果

I would have expected to get 1 assigned to v instead. Same result if you do

var t = (1 == 1 ? 1 : 0);
undefined

有人可以解释为什么这不能按预期工作吗?

Can somebody explain why this does not work as expected?

推荐答案

评估结果 var t = 1 == 1? 1:0; ,例如,Firebug控制台将是 undefined 。但是, t 的值将如预期的那样 1 。在分配后尝试输出 t

The result of evaluating var t = 1 == 1 ? 1 : 0; in, say, the Firebug console will be undefined. However, the value of t will be 1 as expected. Try outputting t after the assignment.

Firebug 在变量时打印结果声明在一个单独的行上:

Firebug will print the result when the variable declaration is on a separate line:

var t;
t = 1 == 1 ? 1 : 0;

这是因为赋值操作的返回值是指定的值。但是,当存在 var 关键字时,返回的是VariableStatement声明的值,其行为如下:

This is because the return value of an assignment operation is the value being assigned. However, when the var keyword is present, what's returning is the value of the VariableStatement declaration, which behaves as follows:

生产 VariableStatement var
VariableDeclarationList ;按如下方式评估
:评估
VariableDeclarationList 。返回
(正常,空,空)。

The production VariableStatement : var VariableDeclarationList; is evaluated as follows: Evaluate VariableDeclarationList. Return (normal, empty, empty).

其中返回(正常,空,空)。指的是内部JavaScript识别的类型,而不是打印到控制台的类型。

Where Return (normal, empty, empty). refers to a type recognized by JavaScript internally, not something that would be printed to the console.

进一步阅读:

http://ecma262-5.com/ ELS5_HTML.htm#Section_12.2

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

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