I have tried this:
// You can pass an array on the addArr method, and each element from the
// passed array is pushed to the array on which addArr was called.
Array.prototype.addArr = function( arr ){
console.log( this );
// As `this` is the array, we use this.push to insert arr's elements
arr.forEach(function(elm){
this.push( elm );
});
// And then finally return this.
return this;
};
The code has been explained using comments, but let me put in straight. I am trying to create a new method on the Array
object called addArr
, which can pass an array [1, 2, 3]
to the method and each of the element is added to the array on which the method was called.
For e.g
var myArr = [1, 2, 3];
myArr.addArr( [4, 5, 6] );
// The output is supposed to be [1, 2, 3, 4, 5, 6]
I am getting Uncaught TypeError: this.push is not a function
, I have tried debugging, this always returns the parent array still it says that push
is not a function.
How can I solve it? I could use libraries like Lodash for these, but I don't prefer to for such a small application.
Thanks!