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 fr.javascript.info — Accès au tableau [-1]

  • Tutoriel
  • JavaScript le langage
  • Divers
  • Proxy et Reflect
retour au cours

Accès au tableau [-1]

Dans certains langages de programmation, nous pouvons accéder aux éléments du tableau à l’aide d’index négatifs, comptés à partir de la fin.

comme ça:

let array = [1, 2, 3];

array[-1]; // 3, le premier élément en partant de la fin
array[-2]; // 2, le second élément en partant de la fin
array[-3]; // 1, le troisième élément en partant de la fin

En d’autres termes, array[-N] est identique à array[array.length - N].

Créez un proxy pour implémenter ce comportement.

Voilà comment cela devrait fonctionner:

let array = [1, 2, 3];

array = new Proxy(array, {
  /* your code */
});

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

// Les autres fonctionnalités de array doivent être conservées
let array = [1, 2, 3];

array = new Proxy(array, {
  get(target, prop, receiver) {
    if (prop < 0) {
      // même si on y accède comme arr[1]
      // prop est une chaîne, il faut donc la convertir en nombre
      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.