Duplicate an array an arbitrary number of times (javascript)

前端 未结 9 1313
臣服心动
臣服心动 2021-01-17 17:35

Let\'s say I\'m given an array. The length of this array is 3, and has 3 elements:

var array = [\'1\',\'2\',\'3\'];

Eventually I will need

9条回答
  •  既然无缘
    2021-01-17 17:45

    Keep it short and sweet

    function repeat(a, n, r) {
        return !n ? r : repeat(a, --n, (r||[]).concat(a));
    }
    
    console.log(repeat([1,2,3], 4)); // [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
    

    http://jsfiddle.net/fLo3uubk/

提交回复
热议问题