Search code examples
javascriptarraysextends

Can't empty Array extended class's elements


I am trying to make a custom Array class by extending the native Array, but I can't figure out how to empty the elements, here's my try.

class MyArray extends Array {
  // for simplicity I just included the bit of code that fails.
  reset () {
    this = []; // fails of course
  }
}

const myarray = new MyArray();
myarray.push(1);
myarray.reset(); // fails because it tries to rewrite `this`

What am I doing wrong ?


Solution

  • Setting the array length to zero will remove all elements.

    class MyArray extends Array {
      // for simplicity I just included the bit of code that fails.
      reset () {
        this.length = 0;
      }
    }
    
    const myarray = new MyArray();
    myarray.push(1,2,3,4);
    
    console.log('before', myarray);
    myarray.reset();
    console.log('after', myarray);

    See How do I empty an array in JavaScript? for more methods of emptying an array.

    This method is mentioned in the accepted answer:

    Method 2 (as suggested by Matthew Crumley)

    A.length = 0
    

    This will clear the existing array by setting its length to 0. Some have argued that this may not work in all implementations of JavaScript, but it turns out that this is not the case. It also works when using "strict mode" in ECMAScript 5 because the length property of an array is a read/write property.