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.

1
  • Thank you. I couldn't find the duplicate because SO's search system does not play nice with [] characters. Commented Sep 23, 2012 at 10:14

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.