Normally I would write
arr = ['choiceA', 'choiceB', 'choiceC', 'choiceD', 'choiceE'];
position = 3;
answer = arr[position];
Just wondering... Is it valid javascript to write the following?
Will it work cross browser?
answer = ['choiceA', 'choiceB', 'choiceC', 'choiceD', 'choiceE'][position];
Yes it is, according to the ECMAScript 5 specification :
MemberExpression :
PrimaryExpression
FunctionExpression
MemberExpression [ Expression ]
MemberExpression . IdentifierName
new MemberExpression Arguments
where PrimaryExpression
is defined as :
PrimaryExpression :
this
Identifier
Literal
ArrayLiteral
ObjectLiteral
( Expression )
So the construct ArrayLiteral[Expression]
is valid.
It does not necessarily mean that it works in every browser (especially IE has something syntax quirks) but you should assume that it does.
Yes, it will. This sintax look weird in a first look, but it is perfectly valid. You are getting a position value from an array that is not being assigned to anything.
It's valid. It's pretty much the same as doing
some_func_that_returns_an_array()[7]
Yes, array literals can be a syntactically valid left part of a member operator . It does work cross-browser.
I find this construct a very readable alternative to a lengthy switch
statement, and use it with object literals as well.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.