【问题标题】:Create new array from total by modulo通过模数从总数创建新数组
【发布时间】:2020-07-16 06:26:04
【问题描述】:
const total = 512;

需要除以数组大小的模

我想要这样的结果,

const newArray = [100, 100, 100, 100, 100, 12];
// const newArray = [sizeofarray, sizeofarray, ...etc].

// 5 乘以 100 和 12

【问题讨论】:

  • 你从哪里得到数组?你试过什么?什么不起作用?
  • 你的原始数组是什么?尺寸对您来说意味着什么?在 javascript 中,数组的大小是该数组的长度。是吗?
  • 我想用 rxjs 史诗函数按总计数分块调用 API,所以我有总计数,我需要生成将在循环中按大小调用 API 的数组。所以我需要上面的 newArray 结果,它是数组的大小。
  • @NinaScholz 该数组是 OP 想要从 total 创建的。 512 = 5 次 10012
  • @ReactNative 所以基本上你有2个信息总数和数组的大小。你想在一个新数组中取模相同的数组大小。对!

标签: javascript arrays lodash


【解决方案1】:

您可以使用此代码

const generator = (total, divider) => {
  let result = Math.round(total/divider);
  let remain = total % divider;
    const tableResult = [];
  for(let i = 0; i < result; i++) {
    tableResult.push(divider);
  }
  tableResult.push(remain);
  return tableResult;
}

console.log(generator(512, 100));

【讨论】:

  • 当总数 = 479 且除数 = 500 时,它不起作用
  • 合计小于除数时,你希望函数返回什么类型的结果
【解决方案2】:

首先你必须创建一个带有模值的数组,然后你可以推送剩余的值

`const total = 512;

 let count = total/100;
 let newArr = new Array(Math.floor(count)).fill(100)
 if(count%1 != 0){
   newArr.push(total%100)
 }

 console.log(newArr) // output`

【讨论】:

  • @ReactNative 请将其设置为正确答案,如果它对您有用,那么它也可以帮助其他用户
  • 当总计 = 479 且页面大小为 500 时,它不起作用
【解决方案3】:

使用Array.from

const gen = (num, size) => {
  const rem = num % size;
  const length = Math.ceil(num / size);
  return Array.from({ length }, (_, i) =>
    (rem !== 0 && i === length - 1) ? rem : size
  );
};

console.log(gen(512, 100));
console.log(gen(500, 100));

【讨论】:

    猜你喜欢
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 2016-04-25
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多