Aleksandro
4/16/2016 5:14:00 PM
On 16/04/16 09:27, Stefan Weiss wrote:
> Aleksandro wrote:
>> On 13/04/16 22:27, JRough wrote:
>>> var arr =[1,2,3,4,5];
>>> function duplicator(arr){
>>> return arr.concat(arr.slice(0));
>>> }
>>> var res = duplicator(arr);
>
> ...
>
>> Try:
>>
>> Array.prototype.duplicate = function ()
>> {
>> this.push.apply(this, this.slice(0))
>> }
>
> Note that this is not equivalent to OP's function.
>
> 1) push() modifies the original array, concat() does not.
>
> 2) It handles sparse arrays badly:
>
> "use strict";
>
> let a = [0,,,,4],
> b = a.slice(0);
>
> dir(a, "a");
> dir(b, "b");
> dir(a.concat(b), "concat()");
> a.push.apply(a, b);
> dir(a, "push() applied");
>
> function dir (arr, label)
> {
> console.log(label + ":");
> for (let i in arr) console.log(` [${i}] = ${arr[i]}`);
> }
>
> Output:
>
> a:
> [0] = 0
> [4] = 4
> b:
> [0] = 0
> [4] = 4
> concat():
> [0] = 0
> [4] = 4
> [5] = 0
> [9] = 4
> push() applied:
> [0] = 0
> [4] = 4
> [5] = 0
> [6] = undefined
> [7] = undefined
> [8] = undefined
> [9] = 4
>
> This is because apply() fills in `undefined` for missing parameters.
>
>
> By the way, ES2015 introduced the spread operator `...`.
> With this operator, you can also write
>
> this.push(...this.slice(0))
>
> instead of
>
> this.push.apply(this, this.slice(0))
>
>
> -- stefan
It could have been what the OP intended though.