我的浏览器在执行 for 循环时冻结,我必须 trim 我的整数

My browser freezes when doing a for loop where I have to trim my integer

我的以下代码需要执行酒精百分比,这在某些时候会输出 43,000004,所以我想 trim 我的数据为 43,0、45,3 等。 但是每次我从 JavaScript 执行任何 trim/parse 函数时,我的浏览器都会冻结。

这是我的代码:

incrementAlcohol() {
  // Create a variable as an array.
  let alcoholData = []

  // Loop through the array until you achieve 40 till 95.
  for (let i = 40; i <= 95; i + 0.1) {
    // Split the first 3 integers in the string to remove the decimals.
    parseFloat(i).toFixed(3)

    // Parse it into a string for the autocomplete component.
    i.toString()

    // Push it into the array.
    alcoholData.push({
      'id': i,
      'name': i + "%"
    })
  }

  // Return the age.
  return alcoholData
},

您可以创建一个产生当前值的生成器函数,然后将其包装在一个数组中。

此外,范围应该为inclusive/exclusive (max = end - step)。

const rangeGenerator = function*(start, end, step, fn) {
  for (let val = start; val < end; val += step) {
    yield fn ? fn(val) : val;
  }
}

let alcoholData = [...rangeGenerator(40, 95, 0.1, (val) => {
  return ((fixed) => ({ id : fixed, name : fixed + "%" }))(val.toFixed(3));
})]

console.log(alcoholData);
.as-console-wrapper { top: 0; max-height: 100% !important; }