Home > Back-end >  Javascript array out of bounds functions
Javascript array out of bounds functions

Time:03-03

in javascript when an index is out of the bounds of the array, it gets extended with undefineds.

Are there any function calls happening behind the scenes?

For example:

var w = []
for (i = 0; i < 10; i  ) {
    w[(i << 4)   15] = i
}

I am trying some prototype poisoning exercises and I noticed an array used with indexes outside its bounds, so I am hoping to modify functions related to this if it is possible.

CodePudding user response:

You can use Proxy:

const arr = new Proxy([], {
    get(target, property) {
        return target[property];
    },
    set(target, property, value) {
        // do your work here ... for example: print some values:
        console.log('oldValue=', target[property]);
        console.log('newValue=', value);
        console.log('index=', property);

        // set the new value - default behaviour
        target[property] = value;

        // Return true if successful. In strict mode, returning false will throw a TypeError exception.
        return true;
    },
});

arr[3] = 'https://sidanmor.com/';

CodePudding user response:

You can override Array.prototype like this:

NOTE the limits in the for loop!

for (let i = -1000; i < 1000; i  ) {
    Object.defineProperty(Array.prototype, i, {
        get() {
            if (this[`_${i}`] === undefined) return 'No value'; // or throw new Error('No value');
            return this[`_${i}`];
        },
        set(v) {
            return this[`_${i}`] = v;
        },
    });
}

const arr = [];

console.log(arr[1]); // No value
arr[1] = 'I have a value'; // set value
console.log(arr[1]); // get the value 'I have a value'
console.log(arr[-1]); // No value
console.log(arr[-100]); // No value
console.log(arr[0]); // No value
console.log(arr[100]); // No value
console.log(arr[10000]); // undefined (because of the limits are -1000 to 1000)

  • Related