3

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>
Scimonster
  • 32,893
  • 9
  • 77
  • 89
nosdalg
  • 571
  • 1
  • 5
  • 23

2 Answers2

4

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;
    }
}
Scimonster
  • 32,893
  • 9
  • 77
  • 89
  • If I pass a set of array element as argument in my function to append whit my current array. Its not working. can you please check. – nosdalg Dec 14 '14 at 10:44
  • Is I need to add as a new questing ? – nosdalg Dec 14 '14 at 10:46
  • 1
    Please [ask a new question](http://stackoverflow.com/questions/ask) if you have another problem. – Scimonster Dec 14 '14 at 10:47
  • please check this questing http://stackoverflow.com/questions/27469074/custom-array-function-using-prototype-new-myarray1-2-3-4-not-working – nosdalg Dec 14 '14 at 12:04
1

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>
KooiInc
  • 119,216
  • 31
  • 141
  • 177