简体   繁体   中英

Array.prototype without modifying 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'd like to make a new Array.prototype method that returns an array without modifying the array it was called upon. So this 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'];
my_array.concat('foo');

concat不会改变原始数组。

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM