Ternary operator with return statements JavaScript [duplicate]

无人久伴 提交于 2019-12-17 17:48:05

问题


I need to return true or false if an option in a drop down selected.

This is my code:

var active = sort.attr('selected') ? return true : return false;

I get an error that the first return is unexpected.

Why?


回答1:


You cannot assign a return statement to a variable. If you want active to be assigned the value true or false, just delete the returns:

var active = sort.attr('selected') ? true : false;

or maybe better:

var active = sort.prop('selected');

since .prop always returns true or false, regardless of the initial tag attribute.




回答2:


You can return from a ternary operator in javascript like this:

return sort.attr('selected') ? true : false;



回答3:


why not just this?

 return sort.attr('selected');



回答4:


Just a comment on your code:

> sort.attr('selected')

seems to be using the jQuery attr method, which used to try and second guess what you wanted and return either the attribute or the property. I think in recent versions it returns the attribute always.

Anyway, the presence of the selected attribute only means that the item (an option element?) is the default selected option, it doesn't mean that it is the currently selected option. For that you need the selected property (jQuery prop method). And since the selected property is a boolean:

> sort.attr('selected') ? true : return false;

can simply be:

 sort.prop('selected');

or without jQuery:

 optionElement.selected;



回答5:


From the docs:

Syntax
condition ? expr1 : expr2
Parameters
condition (or conditions) An expression that evaluates to true or false.
expr1, expr2
Expressions with values of any type.

You should pay attention to the Expressions with values of any type., the return xxx is not an expression.

From wikipedia:

An expression is a syntactic construct, it must be well-formed: the allowed operators must have the correct number of inputs in the correct places, the characters that make up these inputs must be valid, have a clear order of operations, etc. Strings of symbols that violate the rules of syntax are not well-formed and are not valid mathematical expressions.

So, in your case you can use:

return sort.attr('selected') ? true : false


来源:https://stackoverflow.com/questions/19439219/ternary-operator-with-return-statements-javascript

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