在javascript中复制数组的自定义方法

时间:2018-06-06 06:57:30

标签: javascript

如何在javascript中为数组创建一个函数,它的工作方式如下:

const a = [1, 2, 3, 4, 5];
a.duplicate();     // 1, 2, 3, 4, 5, 1, 2, 3, 4, 5

6 个答案:

答案 0 :(得分:3)

使用Array.push

尝试关注

const a = [1, 2, 3, 4, 5];
a.push(...a);
console.log(a);

或者可以添加原型功能( Mutates Original

const a = [1, 2, 3, 4, 5];
Array.prototype.duplicate = function(){
     this.push(...this); // mutates the original array
}
a.duplicate();
console.log(a);

或者可以添加原型功能(创建新

const a = [1, 2, 3, 4, 5];
Array.prototype.duplicate = function(){
     return [...this, ...this]; // creates new
}
console.log(a.duplicate()); // duplicated array
console.log(a); // no change

答案 1 :(得分:2)

在名为Array.prototype的{​​{1}}中添加新功能。

如果要返回新数组



duplicate




或改变原来的



Array.prototype.duplicate = function () {
  return [...this, ...this];
}

const a = [1, 2, 3, 4, 5];

const b = a.duplicate();
console.log(b);




答案 2 :(得分:2)

或者您可以使用[...a,...a]获取新数组而无需修改原始数组



const a = [1, 2, 3, 4, 5];

 

Array.prototype.duplicate = function(){
     return [...this,...this]
}


console.log(a.duplicate())
console.log("Orignal", a)




如果你不知道...是什么,它被称为spread syntax

答案 3 :(得分:0)

创建一个新原型,如下所示:

Array.prototype.duplicate = function() {
    var length = this.length;
    for (var i = 0; i < length; i++)
        this.push(this[i]);
}

答案 4 :(得分:0)

您可以使用此代码 -

function duplicate(coll) {

    return coll.concat(coll);
}

duplicate([1, 2]);

答案 5 :(得分:0)

您可以通过添加到其原型(由Teemu评论)在数组上定义函数。

您的要求不是很清楚,但以下将返回一个数组,如示例所示:

Array.prototype.duplicate = function() {
    return this.concat(this);
}