Skip to content
On this page

Last updated:

JS Array Proxy

Proxy for array elements in js/ts

typescript
const a = [1, 2, 3, 4];

const p = new Proxy([], {
    get(_target, p, receiver) {
        if (p === 'length') {
            return a.length;
        }

        const index = Number(p);
        if (!isNaN(index) && index >= 0 && index < a.length) {
            return a[index];
        }

        return Reflect.get(Array.prototype, p, receiver) || Reflect.get(_target, p, receiver);
    },

    // this is required for internal functions like every
    has(_target, p) {
        const index = Number(p);
        if (!isNaN(index) && index >= 0 && index < a.length) {
            return true;
        }
        return Reflect.has(_target, p) || Reflect.has(Array.prototype, p);
    }
});

console.log('a:', a);
console.log('p.every(a => a > 2):', p.every(a => a > 2)); // Should print false
console.log('p.every(a => a > 0):', p.every(a => a > 0)); // Should print true

// Test normal iteration
console.log('Normal iteration:');
for (let i = 0; i < p.length; i++) {
    console.log(`p[${i}] = ${p[i]}`);
}

// Test with forEach
console.log('forEach test:');
p.forEach((val, idx) => console.log(`forEach: p[${idx}] = ${val}`));

Made with ❤️ using the awesome vitepress