Claudiu Claudiu - 1 year ago 41
Javascript Question

Implement Array-like behavior in JavaScript without using Array

Is there any way to create an array-like object in JavaScript, without using the built-in array? I'm specifically concerned with behavior like this:

var sup = new Array(5);
//sup.length here is 0
sup[0] = 'z3ero';
//sup.length here is 1
sup[1] = 'o3ne';
//sup.length here is 2
sup[4] = 'f3our';
//sup.length here is 5

The particular behavior I'm looking at here is that sup.length changes without any methods being called. I understand from this question that the [] operator is overloaded in the case of arrays, and this accounts for this behavior. Is there a pure-javascript way to duplicate this behavior, or is the language not flexible enough for that?

According to the Mozilla docs, values returned by regex also do funky things with this index. Is this possible with plain javascript?

Answer Source

[] operator is the native way to access to object properties. It is not available in the language to override in order to change its behaviour.

If what you want is return computed values on the [] operator, you cannot do that in JavaScript since the language does not support the concept of computed property. The only solution is to use a method that will work the same as the [] operator.

MyClass.prototype.getItem = function(index)
    return {
        name: 'Item' + index,
        value: 2 * index

If what you want is have the same behaviour as a native Array in your class, it is always possible to use native Array methods directly on your class. Internally, your class will store data just like a native array does but will keep its class state. jQuery does that to make the jQuery class have an array behaviour while retaining its methods.

MyClass.prototype.addItem = function(item)
    // Will add "item" in "this" as if it was a native array
    // it will then be accessible using the [] operator, item);