问题
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 return
s:
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