3 ms·
I think allowing the negative array index, like "items[-1]", would greatly improve the indexing problem. IIRC, JS strings also don't support negative indexes. I
by barosl 12y ago
I think allowing the negative array index, like "items[-1]", would greatly improve the indexing problem. IIRC, JS strings also don't support negative indexes. Is this intended? I think the backward incompatibility that would be led by the change should be tolerable.
And to my personal preferences, I prefer "items[0]" to "items.first()", though the latter is more "english". One of the comments from the post also suggests "items.slice(-1)[0]" as a replacement of "items.last()", but that's another case...
- TazeTSchnitzel 12y agoThat would break backwards-compatibility, however. Arrays are just objects with a magic .length property. As such, I can already do `items[-1] = 'foo';` and it'll create a property named "-1" and set it to "foo".
- barosl 12y agoYeah, that's what I wanted to say by the "tolerable" part. I know arrays, as well as other plain objects in JS, are capable of having arbitrary properties. But hey, how many libraries or code rely on that specific behavior of Array? For the "Greater Good", they can suppress those minor cases and simply extend the magic to the negative integer range. I believe this change can be landed without too much compatibility pain.
- kevingadd 12y agoPutting arbitrary properties on an Array, in practice, turns it into a hashtable or a 'mixed' hashtable+Array (this depends on the JS implementation. Dense array layouts are largely an optimization that the JS runtime applies if it's able to. So you 'can' put arbitrary properties on an Array, but you risk throwing away the benefits you get from using it instead of Object. Sadly the risk of compatibility pain is huge for almost every change you can possibly imagine. I've been participating on es-discuss for a couple years now and tiny, harmless changes end up breaking real web applications on a regular basis - causing the spec committee to have to scratch their heads and figure out a fix. Sometimes there isn't a fix, and they have to rethink.