JavaScript assoc array with negative int keys

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!


Just wrap them in quotes. You can still access with numbers:

var a = {"-1": 'Apple', "-2": 'Orange'}
a[-1]; // Apple;

Tags:

Javascript