GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

No menu could be recovered. Follow the blue links in the page.

This view

  • Original page
  • New address

GeezerVison is showing es.javascript.info — Accediendo a array[-1]

  • Tutorial
  • El lenguaje JavaScript
  • Temas diversos
  • Proxy y Reflect
regresar a la lección

Accediendo a array[-1]

En algunos lenguajes de programación podemos acceder a los arrays usando índices negativos, contando desde el final.

Como esto:

let array = [1, 2, 3];

array[-1]; // 3, el último elemento
array[-2]; // 2, el penúltimo elemento, uno antes del final
array[-3]; // 1, el antepenúltimo elemento, dos antes el final

En otras palabras, array[-N] es lo mismo que array[array.length - N].

Crea un proxy para implementar tal comportamiento.

Así es como debe funcionar:

let array = [1, 2, 3];

array = new Proxy(array, {
  /* tu código */
});

alert( array[-1] ); // 3
alert( array[-2] ); // 2

// el resto de la funcionalidad debe mantenerse igual.
let array = [1, 2, 3];

array = new Proxy(array, {
  get(target, prop, receiver) {
    if (prop < 0) {
      // incluso aunque la accedamos como arr[1]
      // prop es un string, así que necesitamos convertirla a number
      prop = +prop + target.length;
    }
    return Reflect.get(target, prop, receiver);
  }
});


alert(array[-1]); // 3
alert(array[-2]); // 2
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.