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 it.javascript.info — Accesso ad un array[-1]

  • Tutorial
  • Il linguaggio JavaScript
  • Miscellaneous
  • Proxy e Reflect
torna alle lezioni

Accesso ad un array[-1]

In alcuni linguaggi di programmazione, possiamo accedere agli elementi dell’array utilizzando indici negativi, che iniziano il conteggio dalla coda dell’array.

Come nell’esempio:

let array = [1, 2, 3];

array[-1]; // 3, l'ultimo elemento
array[-2]; // 2, il penultimo elemento
array[-3]; // 1, il terzultimo elemento

In altre parole, array[-N] equivale a array[array.length - N].

Create un proxy che implementa questa funzionalità.

Ecco come dovrebbe funzionare:

let array = [1, 2, 3];

array = new Proxy(array, {
  /* il vostro codice */
});

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

// Le altre funzionalità dell'array devono rimanere inalterate
let array = [1, 2, 3];

array = new Proxy(array, {
  get(target, prop, receiver) {
    if (prop < 0) {
      // anche se vi accediamo come arr[1]
      // prop è una stringa, quindi dobbiamo 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.