Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am building JavaScript code to make a custom push function. My new function should act exactly like the original push function.

Here is the code. Please check it.

<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>
like image 581
nosdalg Avatar asked Dec 05 '25 08:12

nosdalg


2 Answers

Because you're not using a native array, the length property doesn't automatically adjust itself. You need to increment it manually, otherwise the next push will just overwrite it:

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

        return this[this.length++]=x;
    }
}
like image 160
Scimonster Avatar answered Dec 07 '25 20:12

Scimonster


If you want to use add instead of push (so, use add as push-alias), just refer to the original Array.prototype.push. See snippet. The snippet also contains a custom addMulti method, 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>
like image 37
KooiInc Avatar answered Dec 07 '25 22:12

KooiInc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!