2

Possible Duplicate:
How would you overload the [] operator in javascript

Is it possible to overload the [] operator for arrays in Javascript?

For instance I would like to modify the behavior of the bracket so that when it accesses an index out of range it returns 0 instead of undedined.

I know I could probably get away with something like this:

function get(array, i) {
    return array[i] || 0;
}

But that's not really modifying the behavior of arrays the way I want.

Community
  • 1
  • 1
rahmu
  • 5,708
  • 9
  • 39
  • 57
  • Thank you. I couldn't find the duplicate because SO's search system does not play nice with `[]` characters. – rahmu Sep 23 '12 at 10:14

2 Answers2

4

Since [] is not an operator, you can't "override" it, but you can add property to Array's prototype, which may be helpful in your specific case. Hovewer, it is a bad practice:

Array.prototype.get = function(i, fallback) { return this[i] || fallback; }

a = [1, 2, 3]

a.get(0, 42)
1

a.get(4, 42)
42
Community
  • 1
  • 1
neoascetic
  • 2,476
  • 25
  • 34
1

[] is not an operator, and you can't override it.

You can override accessors for other javascript objects (that is override ['somespecificvalue'] for writing or reading) but not the [] of arrays.

I'll add I'm glad you can't override it. I don't see the point except in making a whole application unreadable (an application where the basic syntactic elements can't be understood before you've read the whole code to be sure there isn't a change is unreadable).

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758