Duplicate an array an arbitrary number of times (javascript)

前端 未结 9 1318
臣服心动
臣服心动 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条回答
  •  萌比男神i
    2021-01-17 18:11

    if you are inside a loop you can verify the current loop index with the array length and then multiply it's content.

    let arr = [1, 2, 3];
    
    if(currentIndex > arr.length){ 
      //if your using a loop, make sure to keep arr at a level that it won't reset each loop
    
      arr.push(...arr);
    
    }
    

    Full Example: https://jsfiddle.net/5k28yq0L/

提交回复
热议问题