Javascript ternary operator and assignment

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-08 14:30:04

问题


I get unexpected result for this simple JavaScript assignment statement:

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

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?


回答1:


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 will print the result when the variable declaration is on a separate line:

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

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:

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

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

Further reading:

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




回答2:


It works perfectly:

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

You could say that the return value of the assignment operation is undefined, not the value of t.


Edit: But actually if I read the specification correctly, it seems that it should return the value of the expression.

As @T.J. Crowder mentioned, it seems the var is responsible for the undefined value. But that does not mean that you should not use var. The code you wrote is 100% correct.

This goes more into the inner workings of the language and I think that is not what you are interested in. Bur for more information about that, have a look at the comments.




回答3:


In old javascript parsers we need to conclude the condition in parentheses:

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



回答4:


This code works fine:

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

Check here. It shows 1.



来源:https://stackoverflow.com/questions/5080242/javascript-ternary-operator-and-assignment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!