Martin Hansen Martin Hansen - 4 months ago 12x
Javascript Question

Getter/setter on javascript array?

Is there a way to get a get/set behaviour on an array? I imagine something like this:

var arr = ['one', 'two', 'three'];
var _arr = new Array();

for (var i=0; i < arr.length; i++) {
function(index) {
//Do something
return _arr[index];
function(index, val) {
//Do something
_arr[index] = val;


Array access is no different to normal property access. array[0] means array['0'], so you can define a property with name '0' and intercept access to the first array item through that.

However, that does make it impractical for all but short, more-or-less-fixed-length Arrays. You can't define a property for “all names that happen to be integers” all in one go.