【问题标题】:Split Array into Two-Dimensional Array: Is There a Better Solution?将数组拆分为二维数组:有更好的解决方案吗?
【发布时间】:2016-02-26 16:18:31
【问题描述】:

我用下面的函数解决了来自 FreeCodeCamp 的算法挑战,但我想知道这是否是解决问题的“好”方法,最具体地说,因为我将计数器设置为 i+=0 并从头部拼接索引.我是否在这里创建了反模式?有什么更合乎逻辑的吗,你能解释一下原因吗?提前感谢您的帮助!

function chunk(arr, size) {
  var newArr = [];
  for (i=0; i<arr.length; i+=0) { 
      var sliced = arr.slice(i, size);
      newArr.push(sliced);
      arr.splice(0, size);
  }
  return newArr;
}
chunk([0, 1, 2, 3, 4, 5, 6, 7, 8], 4);
returns--> [ [ 0, 1, 2, 3 ], [ 4, 5, 6, 7 ], [ 8 ] ]

【问题讨论】:

  • 您可以查看Array.slice()。此外,如果这个问题的目的是寻求改进,您应该尝试 CodeReviews
  • 我投票决定将此问题作为离题结束,因为它要求进行代码审查。在 codereview.stackexchange.com 上询问

标签: javascript arrays


【解决方案1】:

我是否在这里创建了反模式?有什么更合乎逻辑的吗,你能解释一下原因吗?

您的代码包含一些可改进的部分

function chunk(arr, size) {
  //newWhatever, myWhatever, ... look for a better naming like `out` or `result` 
  //or in this case `chunks` would describe the content of the variable
  var newArr = [];

  //you initialize `i` without the var-keyword, therefore you populate/pollute the global namespace
  //and instead of calculating i+=0, you can leave this part empty:
  //for(var i=0; i<arr.length; ){
  for (i=0; i<arr.length; i+=0) { 
      var sliced = arr.slice(i, size);
      newArr.push(sliced);

      //splicing (with P) is often a thing that should be avoided, 
      //- it is destructive (it destroys the input-array)
      //- it is slow, cause the engine has to allocate new memory 
      //  and copy the remaining elements over to this memory,
      //  and garbage-collect the old memory
      arr.splice(0, size);
  }
  return newArr;
}

更好的解决方案是:

function chunk(arr, size) {
    for(var chunks=[], i=0; i<arr.length; i+=size)
        chunks.push(arr.slice(i, size));
    return chunks;
}

假设输入是正确的。

为了完整性,您应该添加一些输入验证。该 arr 就位,可以切片,并且具有长度属性。
并且该大小是一个大于 0 的整数,否则代码可能会产生奇怪的结果。

function chunk(arr, size) {
    //checks if arr is not empty and arr.slice is not empty 
    //and casts the length-property to int
    //if anything "fails" len = 0;
    var len = (arr && arr.slice && arr.length)|0;

    //check if size is > 1 and is an integer
    if(size !== Math.floor(size) || size < 1)
        throw new Error("invalid chunl-size: "+size);

    for(var chunks=[], i=0; i<len; i+=size)
        chunks.push(arr.slice(i, size));
    return chunks;
}

【讨论】:

    【解决方案2】:

    也许是递归?

    function chunk(arr, size, out) {
    
      // if the output array hasn't been passed in
      // create it
      out = out || [];
    
      // if there are no elements in the input array
      // return the output array
      if (!arr.length) return out;
    
      // push the "head" of the input array to the
      // output array
      out.push(arr.slice(0, size));
    
      // call chunk again with the "tail" of the input array
      return chunk(arr.slice(size), size, out);
    }
    

    DEMO

    【讨论】:

      【解决方案3】:
      function chunk(arr, size) {
          var subArrayCount = arr.length / size;
          var res = [];
          for (i = 0; i < subArrayCount; i++) {
              var from = size * i;
              var to = (size * (1 + i));
              console.log(to)
              var sliced = arr.slice(from, to);
              res.push(sliced);
          }
          return res;
      }
      chunk([0, 1, 2, 3, 4, 5, 6, 7, 8], 4);
      returns--> [ [ 0, 1, 2, 3 ], [ 4, 5, 6, 7 ], [ 8 ] ]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-17
        • 1970-01-01
        • 2020-11-18
        • 1970-01-01
        • 2014-08-28
        • 2014-02-16
        • 2021-12-24
        相关资源
        最近更新 更多