On Wed, May 5, 2010 at 8:27 AM, Jordan Osete <jordan.os...@yahoo.fr> wrote:
> I've been wondering for some time if there couldn't be a way to index arrays
> from the last element directly. Currently if you have an array lost in a
> deep objects hierarchy, you have to refer to it twice, once to access the
> array itself, and once again to access its length:

A temporary helps here, as is often the case with deep hierarchies.

> var lastItem =
>
> myObject.anArray[ myObject.anArray.length - 1 ];
>
> myObject.anArray[ myObject.anArray.length - 2 ] = "foo";

a = myObject.anArray; a[a.length - 1];

a[a.length - 2] = "foo";

> As it seems hard to change the core language to be able to access stuff with
> negative indexes, the idea would be just to add a method to ease getting /
> setting of items based on the length of the array:

It would be incompatible, since a[-1] means the same thing for arrays
as for objects: the property named "-1".

You can do it with slice and splice, though, if you don't want to just
use a temporary:

>  //get the last element, same as .last( 0 )
>
> var lastItem = myObject.anArray.last();

myObject.anArray.slice(-1)[0]

> myObject.anArray.last( 1, "foo" );

myObject.anArray.splice(-2, 1, "foo");

With destructuring assignment, the slice usage gets to be a little
more natural, though it still constructs an array unless there is some
analysis done of the call site.

TBH, I don't think that end-based access to arrays other than to
append, a la Array.prototype.push, is common enough to warrant adding
to the language.  You could decorate Array.prototype with your own
|last| method (including the unusual get/set overload) if you wanted,
and use ES5's property-descriptor facilities to keep it from affecting
iteration.

Mike
_______________________________________________
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to