我的浏览器在执行for循环时冻结,在该循环中必须修剪整数[closed]

问题描述 投票:-1回答:1

我的以下代码需要执行酒精百分比,在某些时候输出为43000004,所以我想将数据修整为43,0,45,3等。但是每次我从JavaScript执行任何修剪/解析功能时,浏览器都会冻结。

这是我的代码:

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
},
javascript arrays vue.js parsing trim
1个回答
1
投票

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

此外,范围应该为包含/排除(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; }
© www.soinside.com 2019 - 2024. All rights reserved.