1
0

TypeScript(JavaScript)で配列の開始indexを1始まりに偽装する

Last updated at Posted at 2024-02-25

Proxyオブジェクトを使用して実現します

const org = [1, 3, 5];

const array: any[] = new Proxy(org, {
  get(target: any[], prop: PropertyKey) {
    const index = Number(prop);
    if (!isNaN(index)) {
      // プロパティが数値であれば1を引く
      prop = index - 1;
    }
    return Reflect.get(target, prop);
  },
  set(target: any[], prop: PropertyKey, value) {
    const index = Number(prop);
    if (!isNaN(index)) {
      // プロパティが数値であれば1を引く
      prop = index - 1;
    }
    return Reflect.set(target, prop, value);
  }
});

array[2] = 9;
for (let i = 1; i <= array.length; i++) {
  console.log(i, array[i]); // 1, 9, 5 を順に出力
}

console.log("元の配列は0始まり");
for (let i = 0; i < org.length; i++) {
  console.log(i, org[i]); // 1, 9, 5 を順に出力
}

実行結果

1 1
2 9
3 5
元の配列は0始まり
0 1
1 9
2 5
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0