【问题标题】:Sorting array in chunks doesn't work [duplicate]按块排序数组不起作用[重复]
【发布时间】:2018-09-13 18:51:24
【问题描述】:

看似简单的任务,但行不通。我有一个已知长度的数组(比如 9)和一个块大小(比如 3)。数组总是可以被那个块整除,不需要测试。初试:

const chunked = [];
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

for(let i=0; i<3; i++) { 
    chunked[i] = arr.slice(i*3, 3);
}

console.log(chunked);

但后来意识到slice() 可能会覆盖它的输入,所以:

const chunked = [];
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

for(let i=0; i<3; i++) { 
    let temp = arr.slice();
    chunked[i] = temp.slice(i*3, 3);
}

console.log(chunked);

但仍然只创建第一个块...我的错误在哪里?

【问题讨论】:

  • slice 的第二个参数不是长度,而是结束索引。
  • 哦,是的,没有意识到这一点。这工作for(let i=0; i&lt;3; i++) { let temp = res.slice(); res2[i] = temp.slice(i*3, (i+1)*3); }非常感谢
  • 我知道类似的 SO 问题,但这些似乎太复杂了。在我的评论中,这种方式似乎更简单、更容易理解

标签: javascript


【解决方案1】:

slice() 方法返回数组一部分的浅拷贝 进入从开始到结束(不包括结束)选择的新数组对象。 原数组不会被修改。

arr.slice([begin[, end]])

您可以从 0 循环到数组的长度,然后按块大小递增。

喜欢:

const chunked = [];
const chuckSize = 3;
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

for (let i = 0; i < arr.length; i += chuckSize) {
  chunked.push(arr.slice(i, i + chuckSize));
}

console.log(chunked);

【讨论】:

    【解决方案2】:

    尝试关注

    const chunked = [];
    const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    
    for(let i=0; i<3; i++) { 
        let temp = arr.slice();
        
        chunked[i] = temp.slice(i*3, (i+1)*3); // Need to set appropriate begin and end
    }
    
    console.log(chunked);

    供参考,Array.slice

    【讨论】:

      【解决方案3】:

      slice 的第二个参数是您可能假设的结束索引(不是长度)。你可以找到文档here

      【讨论】:

        【解决方案4】:

        函数sliceslice(firstIndex, lastIndex + 1)为参数

        请使用以下代码:

         const chunked = [];
            const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
            
            for(let i=0; i<3; i++) { 
                chunked[i] = arr.slice(i*3, i*3 + 3);
            }
            
            console.log(chunked);

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-12-12
          • 2018-08-14
          • 2021-09-04
          • 2017-11-08
          • 2013-12-14
          • 2020-12-19
          • 2012-07-06
          相关资源
          最近更新 更多