最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript - clone array inside itself - Stack Overflow

programmeradmin5浏览0评论

I have an array ["0", "1", "2"] and I need to create function that makes it
["0", "1","2", "0", "1", "2"]. I wrote that clone function:

arr = [0, 1, 2];
arr.clone = function() {
    var b = [];
    for (var i = 0; i < arr.length; i++) {
        b.push(arr[i]);
    }
    var c = b.concat(b);
    return c;
}
arr.clone();

Am I doing it right? Maybe there's a better or shorter way to clone the elements?

I have an array ["0", "1", "2"] and I need to create function that makes it
["0", "1","2", "0", "1", "2"]. I wrote that clone function:

arr = [0, 1, 2];
arr.clone = function() {
    var b = [];
    for (var i = 0; i < arr.length; i++) {
        b.push(arr[i]);
    }
    var c = b.concat(b);
    return c;
}
arr.clone();

Am I doing it right? Maybe there's a better or shorter way to clone the elements?

Share Improve this question asked Sep 6, 2013 at 8:31 Alexandra VorobyovaAlexandra Vorobyova 1072 silver badges7 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 11

You only have to use concat() by itself, since it builds a new array:

var arr = [0, 1, 2];
arr = arr.concat(arr);  // [0, 1, 2, 0, 1, 2]
const arr = [0, 1, 2]
const binedOne = [ ...arr, ...arr]

With es6, we can use the spread operator.

// try this
Array.prototype.self2 = function () {
    return ( Array.prototype.push.apply( this, this ), this );
};
console.log( [1,2,"a"].self2() );
//
//  [1, 2, "a", 1, 2, "a"]
//

Alternatively, you can also write the concat method, in this way:

let arrayA = [0, 1, 2];
arr = [].concat(arr, arr);
console.log(arr);

Frédéric Hamidi's answer is probably the best answer if all of your target browsers support Array.concat method, and you don't mind creating a new array.

Here's how you can keep the old array reference without creating a new array, and is fully cross-browser.

arr.push.apply(arr, arr);
发布评论

评论列表(0)

  1. 暂无评论