I need to create a Javascript function to create a custom push function

I am creating JavaScript code to create a custom push function. My new function should act exactly the same as the original push function.

Here is the code. Please check it out.

<script type="text/javascript">

function MyArray(){
    this.add=function(x){

        return this[this.length]=x;
    }
}

MyArray.prototype=Array.prototype;

var collection = new MyArray();


collection.push(44);

collection.add(56); // this is not working. 

collection.push(77);
collection.push(88);

console.log(collection);

</script>

      

+3


source to share


2 answers


Since you are not using your own array, the property is length

not automatically configured. You need to increase it manually, otherwise the following will push

just overwrite it:



function MyArray(){
    this.add=function(x){

        return this[this.length++]=x;
    }
}

      

+4


source


If you want to use add

instead push

(so use add

like push

-alias), just refer to the original Array.prototype.push

. See Snippet. The snippet also contains its own method addMulti

derived from Array.prototype.push

.



function MyArray(){ }
MyArray.prototype = Array.prototype;
MyArray.prototype.add = Array.prototype.push;

// custom addMulti method, derived from Array.prototype.push
MyArray.prototype.addMulti = function addMulti(arrayOfValues){
    [].push.apply(this, arrayOfValues);
};

var foo = new MyArray;
// add and push both work
foo.add(13);
foo.push(17);
foo.add(15,16,18);
foo.push(112);
// push an array of values
foo.addMulti([200,300,400,500]);

var report = new MyArray;
report.add('<code>foo.length: ',foo.length, ', foo: [', foo, ']</code>');
document.querySelector('#result').innerHTML = report.join('');
      

<div id="result"><div>
      

Run codeHide result


+1


source







All Articles