配列[-1]にアクセスする
一部のプログラミング言語では、末尾から数えたインデックスを使用して配列要素にアクセスできます。
以下のような形で
let array = [1, 2, 3];
array[-1]; // 3, the last element
array[-2]; // 2, one step from the end
array[-3]; // 1, two steps from the end
言い換えると、array[-N]
は array[array.length - N]
と同じです。
その動作を実装するためのプロキシを作成します。
こうやります
let array = [1, 2, 3];
array = new Proxy(array, {
/* your code */
});
alert( array[-1] ); // 3
alert( array[-2] ); // 2
// Other array functionality should be kept "as is"
let array = [1, 2, 3];
array = new Proxy(array, {
get(target, prop, receiver) {
if (prop < 0) {
// even if we access it like arr[1]
// prop is a string, so need to convert it to number
prop = +prop + target.length;
}
return Reflect.get(target, prop, receiver);
}
});
alert(array[-1]); // 3
alert(array[-2]); // 2