【问题标题】:Replicate array to certain length in javascript在javascript中将数组复制到一定长度
【发布时间】:2018-11-09 22:00:42
【问题描述】:

我有这个数组 [1,2,3]

我希望能够将其长度设置为 7

结果是 [1,2,3,1,2,3,1]。

有人吗?

const arr = [1,2,3];

// Something like
arr.resize(7);

console.log(arr); // [1,2,3,1,2,3,1]

编辑: 根据下面的 chevybow 答案,我编写了这个函数来满足我的需求。

// Immutable
Array.prototype.resize = function(size) {
    const array = Array(size);
    for(let i = 0; i < size; i++) {
        array[i] = this[i%this.length];
    }
    return array;
}

// Mutable
Array.prototype.resize = function(size) {
    const array = this.slice(0);
    this.length = size;
    for(let i = 0; i < size; i++) {
        this[i] = array[i%array.length];
    }
}

这些还好吗?或者你认为把它放在链上不是一个好主意,如果是这样,为什么?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    您可以使用模算术循环直到最终数组的长度,然后使用索引基本上循环并将其推送到新数组中

    使用当前数组值 % array.length 将通过圆周运动获得数组的当前位置

    let num = 7;
    let array = [1,2,3];
    let result = [];
    for(let i = 0; i < num; i++){
      result.push(array[i%array.length]);
    }
    
    console.log(result)

    【讨论】:

    • 这是一个很棒的方法!
    【解决方案2】:

    一个简单的while循环就足够了:

    function repeat(arr, toLength) {
      let output = [...arr];
      while (output.length < toLength) output = [...output, ...arr];
      return output.slice(0, toLength);
    }
    console.log(repeat([1, 2, 3], 7));
    console.log(repeat([1, 2, 3], 2));

    【讨论】:

      【解决方案3】:

      这个版本怎么样:

      const nums = [1, 2, 3];
      
      function resize(arr, length) {
        let position = 0;
        return Array.from(Array(length)).reduce((acc, _, i) => {
          return acc.concat(arr[i % arr.length]);
        }, []);
      }
      
      console.log(resize(nums, 7));

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-21
        • 2015-04-13
        • 2015-04-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-01
        • 1970-01-01
        相关资源
        最近更新 更多