Reference to slice of an array

How to get the reference to a slice of an array?

var A = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
A.mySlice = function(l, h){return this.slice(l,h)};

var B = A.mySlice(1,5); // ["b", "c", "d", "e"]

It works for direct slices derived from A. But, how to get it for all slices derived? (in this case for B)

B.mySlice = function(l, h){return this.slice(l,h)};

A[3] = 33;
A.mySlice(1,5) // ["b", "c", 33, "e"] => ok
B.mySlice(0,3) // ["b", "c", "d"] => I would want ["b", "c", 33]


I don’t think you can do this with native JS arrays (well, not in a straightforward manner anyway).

I think the cleanest approach would be going back and using custom objects to represent the slices. Perhaps something along these lines:

function ArraySlice(arr, lo, hi){
    this.arr = arr;
    this.lo = lo;
    this.hi = hi;
    this.length = hi - lo;
ArraySlice.prototype._contains = function(ix){
    return this.lo + ix < this.hi;
ArraySlice.prototype.get = function(ix){
    if (this._contains(ix)){
        return this.arr[this.lo + ix];
        return; //undefined
ArraySlice.prototype.set = function(ix, value){
    if (this._contains(ix)){
        return (this.arr[this.lo + ix] = value);
        return; //undefined

var a = [0,1,2,3,4,5];
var b = new ArraySlice(a, 1, 3);

a[2] = 17;
console.log( b.get(1) );

Of course, this loses the convenient [] syntax and the objects aren’t arrays anymore but subclassing Array is annoying and error prone and I don’t believe there is a cross-browser way to do operator overloading.

Leave a Reply

Your email address will not be published. Required fields are marked *