Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript assoc array with negative int keys

Tags:

I don't seem to be able to define something like:

var a = {-1: 'Apple', -2: 'Orange'} 

my Safari complains about a syntax error near '-'. Parens don't help either, i.e. {(-1): ... - in that case Safari doesn't like the opening paren.

If I want the keys to be just ints, not strings, what is the proper way of constructing an assoc array, if any?

like image 305
mojuba Avatar asked Nov 18 '11 12:11

mojuba


1 Answers

See section 11.1.5 of ECMAScript Language Specification: there you will see that PropertyName may indeed be a NumericLiteral, but section 7.8.3 of the specification indicates that NumericLiteral may not start with the minus sign. What looks like negative "literals" in your example are actually expressions composed of the unary operator - and NumericLiterals.

However, PropertyName may not be an expression: it can only be an identifier name, a numeric literal or a string literal which suggests that you can write

{'-1': 'Apple', '-2': 'Orange'} 

Thanks to GetFree for finding the correct explanation!

like image 149
Adam Zalcman Avatar answered Oct 10 '22 23:10

Adam Zalcman