Array.prototype without modifying the original array

I want to create a new Array method without modifying the original array.

my_array.push('foo') //modifies my_array
my_array.slice(2) //returns a new array without modifying my_array

      

I would like to create a new Array.prototype method that returns an array without modifying the array it was called on. This way it would be possible:

//[define new method here] Array.prototype.add_foo = function() {...
var my_array = ['poo'];

my_array.add_foo(); //would return ['poo', 'foo'];
my_array; //would return ['poo'];

      

+3


source to share


2 answers


Array.prototype.add_foo = function(){
    var ret = this.slice(0); //make a clone
    ret.push("foo"); //add the foo
    return ret; //return the modified clone
}

      



+2


source


my_array.concat('foo');

      



concat

does not modify the original array.

+3


source







All Articles