使用javascript生成一个数值范围为7的倍数的数组

324*_*423 -2 javascript ecmascript-6

我想用最现代的方式制作这样的阵列

const nextchunk = [];
nextchunk[0] = [0, 6];
nextchunk[1] = [7, 13];
Run Code Online (Sandbox Code Playgroud)

每个nextchunk必须有7个位置,如图所示.这些代表稍后在代码中的限制查询.所以nextchunk[1]拿出第7 - 13项,nextchunk[2]14 - 20出局

我希望能够nextchunk[20]在运行时调用并让它返回正确的值.

Jon*_*lms 5

   function chunks(size) {
     return function getChunk(index) {
       return [size * index, size * (index + 1) - 1];
     }
   }

   const nextchunk = chunks(7);
   console.log(
      nextchunk(0), 
      nextchunk(1), 
      nextchunk(20)
   );
Run Code Online (Sandbox Code Playgroud)

您可以轻松计算出该值.在实际需要之前无需生成它.如果你真的需要数组,那么很容易用上层助手构建它:

  const nextchunk = Array.from({length: 21}, (_, i) => chunks(7)(i));
  console.log(nextchunk[20]);
Run Code Online (Sandbox Code Playgroud)

  • @mohammad它提高了可读性并有助于调试. (2认同)