Proxy arrays part2

by Richard Hunter

JavaScript

/*
    Simple objects appear to be well behaved, however I have encountered things which seem a bit weird
    when dealing with arrays.
*/

var arrayTarget = ['hello', 'world'];

var arrayHandler = {
    set : function (target, property, value, receiver) {
        console.log("set:", property, value);
        target[property] = value;
    }  
};

var proxyArray = new Proxy(arrayTarget, arrayHandler);

//  this outputs '0'!
console.log("length of proxyArray:", proxyArray.length);
//  this outputs an empty array
console.log('proxyArray:', proxyArray);
//  but this outputs 'hello' 'world' showing that there is something in there!
console.log("access proxy array by index:", proxyArray[0], proxyArray[1]);

//  now lets attempt to push to the array
// this appears to work
proxyArray.push('blah');

//  but this outputs an empty array.
console.log('proxyArray after push():', proxyArray);

// this outputs 'blah' !
console.log('proxyArray[0] after push():', proxyArray[0]);

//  the length is still 0!
console.log('proxyArray.length after push():', proxyArray.length);


//  and what about the original array?

//  this outputs ["blah"] !
console.log('arrayTarget after push:', arrayTarget);

//  length is 1
console.log('arrayTarget.length after push:', arrayTarget.length);

/*
It's hard to know exactly what to makes of the above, but it sure isn't what we wanted!
We wanted to push to the array, but instead have obliterated it's original contents.
*/




/*
var handler = {
    set : function (target, index, value) {
        console.log("set", index, value);
        target[parseInt(index)] = value;
    },
    get : function (target, property) {
        console.log("get");
        if(property === 'length') {
            return target.length;
        }
    }
};

var proxy = new Proxy(model, handler);



console.log(proxy.length);

*/