【问题标题】:Most efficient (compact) way to create repetitive arrays in javascript or php?在 javascript 或 php 中创建重复数组的最有效(紧凑)方法?
【发布时间】:2015-09-05 09:58:31
【问题描述】:

假设我需要一个包含许多重复元素的数组,如下所示:

[3,3,3,3,3,8,8,8,8,5,5,5,5,5,5](即五个 3、四个 8 和六个 5)

在python中,你可以像这样非常优雅地定义它:

[3]*5+[8]*4+[5]*6

在 JS 或 PHP 中有类似的构造吗?

在这个例子中,明确定义整个数组并不是什么大问题。但是如果有很多元素,有很多重复,这可能会变得非常乏味(更不用说容易了)。我希望我的代码大小保持相等,无论数组有五个 3 还是 500。

在JS中,我能想到的最短的是:

var a = [];
[[3,5],[8,4],[5,6]].forEach(function(x){while(x[1]--)a.push(x[0])});

在 PHP 中类似:

foreach(array(3=>5,8=>4,5=>6) as $d=>$n) while($n--) $a[]=$d;

显然,这不会为可读性得分。有没有更好的方法(最好是某种语言结构)来做到这一点?

【问题讨论】:

    标签: javascript php arrays repeat


    【解决方案1】:

    JavaScript

    可读性和可重用性的最佳方式可能是为数组“乘法”定义一个函数,例如这个函数以指数方式实现

    function arrMultiply(arr, i) {
        var arr_out = [];
        if (i & 1)
            arr_out = arr_out.concat(arr);
        while ((i >>>= 1) > 0) {
            arr = arr.concat(arr);
            if (i & 1)
                arr_out = arr_out.concat(arr);
        }
        return arr_out;
    }
    

    现在你可以concat一起“multiplied”数组

    arrMultiply([3], 5).concat(arrMultiply([8], 4)).concat(arrMultiply([5], 6));
    // [3, 3, 3, 3, 3, 8, 8, 8, 8, 5, 5, 5, 5, 5, 5]
    

    如果你真的想要,你可以扩展 Arrayprototype 以包含 arrMultiply function 这将使你的语法更接近到你已经在使用的,

    Array.prototype.mul = function (i) {return arrMultiply(this, i);};
    
    [3].mul(5).concat([8].mul(4)).concat([5].mul(6));
    // [3, 3, 3, 3, 3, 8, 8, 8, 8, 5, 5, 5, 5, 5, 5]
    

    【讨论】:

    • 在这个答案中,我将操作称为 "multiplication",因为我们正在从 Python 实现 * 的行为,但重新阅读这个答案我认为使用 repeat 这个词可能会更好,因为在这种情况下 multiply 可能会模棱两可(想想 scalar multiplication, dot product, cross product , 重复等)
    【解决方案2】:

    在 JavaScript 中:

    Array.apply(null, Array(c)).map(function () {
        return v;
    });
    

    function f(c, v) {
        return Array.apply(null, Array(c)).map(function () {
            return v;
        });
    }
    
    document.write(f(5, 3).concat(f(4, 8)).concat(f(6, 5)));

    ".apply()" 允许以数组的形式将参数传递给函数,大致如下:

    say.apply(null, ['hello', 'world'])
    

    等同于:

    say('hello', 'world')
    

    因此,由于Array(3) 给出[undefined x 3]

    Array.apply(null, Array(3))
    

    等同于:

    Array(undefined, undefined, undefined)
    

    为什么需要它?参考JavaScript "new Array(n)" and "Array.prototype.map" weirdness

    【讨论】:

      【解决方案3】:

      您可以使用 array_fill() 将值填充到数组中,然后将 array_merge() 填充到结果数组中,例如

      <?php
      
          $arr = [[3,5],[8,4],[5,6]];
          $result = [];
          foreach($arr as $v)
              $result = array_merge($result, array_fill(0, $v[1], $v[0]));
      
          print_r($result);
      
      ?>
      

      输出:

      Array
      (
          [0] => 3
          [1] => 3
          [2] => 3
          [3] => 3
          [4] => 3
          [5] => 8
          [6] => 8
          [7] => 8
          [8] => 8
          [9] => 5
          [10] => 5
          [11] => 5
          [12] => 5
          [13] => 5
          [14] => 5
      )
      

      【讨论】:

        【解决方案4】:

        一个怪异的(仅数字)x-)

        document.write(
          '<pre>' + JSON.stringify(
            makeArray('[1x1,3x4,42x3]')
          ) + '</pre>'
        );
        
        function makeArray (expr) {
          return JSON.parse(
            expr.replace(/(\d+)x(\d+)/g, function ($0, $1, $2) {
              return $1 + new Array(+$2).join(','+$1);
            })
          );
        }

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-12-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-12-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多