代码之家  ›  专栏  ›  技术社区  ›  Andrew Grimm Alex Wayne

在JavaScript中多次重复包含多个元素的数组

  •  20
  • Andrew Grimm Alex Wayne  · 技术社区  · 7 年前

    在Ruby里,你可以

    irb(main):001:0> ["a", "b", "c"] * 3
    => ["a", "b", "c", "a", "b", "c", "a", "b", "c"]
    

    我查了洛达斯图书馆,没有找到任何直接适用的。 Feature request: repeat arrays. 是将其添加到lodash的功能请求,并且给出了最佳解决方案

    const arrayToRepeat = [1, 2, 3];
    const numberOfRepeats = 3;
    const repeatedArray = _.flatten(_.times(numberOfRepeats, _.constant(arrayToRepeat)));
    

    问题 Most efficient way to create a zero filled JavaScript array? Create an array with same element repeated multiple times 重点是重复一个元素多次,而我想重复一个数组有多个元素。

    7 回复  |  直到 7 年前
        1
  •  27
  •   CertainPerformance    7 年前

    不需要任何图书馆,你可以用 Array.from [].concat 传播:

    const makeRepeated = (arr, repeats) =>
      [].concat(...Array.from({ length: repeats }, () => arr));
      
    console.log(makeRepeated([1, 2, 3], 2));

    在较新的浏览器上,可以使用 Array.prototype.flat 而不是 [].concat(... :

    const makeRepeated = (arr, repeats) =>
      Array.from({ length: repeats }, () => arr).flat();
      
    console.log(makeRepeated([1, 2, 3], 2));
        2
  •  15
  •   ibrahim mahrir    7 年前

    你可以用 Array 构造函数及其 fill 方法来填充要重复的数组的次数,然后 concat

    const repeatedArray = [].concat(...Array(num).fill(arr));
    

    注: 在较旧的浏览器(ES6之前)上,可以使用 Function#apply 将使用作为参数传递给它的每个子数组进行调用):

    var repeatedArray = [].concat.apply([], Array(num).fill(arr));
    

    例子:

    const arrayToRepeat = [1, 2, 3];
    const numberOfRepeats = 3;
    
    const repeatedArray = [].concat(...Array(numberOfRepeats).fill(arrayToRepeat));
    
    console.log(repeatedArray);
        3
  •  13
  •   Slai    5 年前

    const repeat = (a, n) => Array(n).fill(a).flat(1)
    
    console.log( repeat([1, 2], 3) )

    const repeat = (a, n) => n ? a.concat(repeat(a, --n)) : [];
    
    console.log( repeat([1, 2], 3) )
        4
  •  8
  •   Gonzalo.-    7 年前

    我的第一个想法是创建这样一个函数

    let repeat = (array, numberOfTimes) => Array(numberOfTimes).fill(array).reduce((a, b) => [...a, ...b], [])
    console.log(repeat(["a", "b", "c"], 3))

    fill 方法和 reduce

    flatten 但目前还没有浏览器支持

        5
  •  1
  •   wiesion    7 年前

    不幸的是,这在JS中是不可能的(同样操作符重载也是不可能的,所以我们不能使用类似 Array.prototype.__mul__

    const seqFill = (filler, multiplier) => 
      Array(filler.length * multiplier)
      .fill(1)
      .map(
        (_, i) => filler[i % filler.length]
      );
    
    console.log(seqFill([1,2,3], 3));
    console.log(seqFill(['a','b','c', 'd'], 5));

    或者通过另一种方式连接到数组原型,您可以使用 Array#seqFill(multiplier) ,这可能是最接近ruby语法的方法(rb基本上可以用操作符重载完成所有事情,但是JS不能):

    Object.defineProperty(Array.prototype, 'seqFill', {
      enumerable: false,
      value: function(multiplier) {
        return Array(this.length * multiplier).fill(1).map((_, i) => this[i % this.length]);
      }
    });
    
    console.log([1,2,3].seqFill(3));
        6
  •  1
  •   Bergi    7 年前

    [].concat + Array.from({length: 3}, …) / fill()

    function* concat(iterable) {
        for (const x of iterable)
            for (const y of x)
                yield y;
    }
    function* repeat(n, x) {
        while (n-- > 0)
            yield x;
    }
    
    const repeatedArray = Array.from(concat(repeat(3, [1, 2, 3])));
    

    function* concatRepeat(n, x) {
        while (n-- > 0)
            yield* x;
    }
    
    const repeatedArray = Array.from(concatRepeat(3, [1, 2, 3]));
    
        7
  •  1
  •   Vignesh Raja    7 年前

    Array.fill() Array.from() IE . MDN Docs for Reference

    方法1 Array.prototype.push )在数组中输入相同的值。

    function mutateArray(arr,n)
    {
        var temp = [];
        while(n--) Array.prototype.push.apply(temp,arr);
        return temp;
    }
    var a = [1,2,3,4,5];
    console.log(mutateArray(a,3));

    方法2 String.repeat()

    注意 :的 repeat IE公司 Android webviews

    function mutateArray(arr,n)
    {
        var arr = (arr.join("$")+"$").repeat(n).split("$");
        arr.pop(); //To remove the last empty element
        return arr;
    }
    var a = [1,2,3,4,5];
    console.log(mutateArray(a,3));
        8
  •  1
  •   Kamil Kiełczewski    6 年前

    尝试

    Array(3).fill(["a", "b", "c"]).flat()
    

    console.log( Array(3).fill(["a", "b", "c"]).flat() );