Javascript-在百分比函数之后使用Math.round

我有一个计算函数,用于确定数组中两个值之间的百分比差异。

完成计算后,返回的值采用十进制形式,例如

0: 6.439999737456044
​
1: 7.7490311455816805
​
2: 2.3720164855984383
​
3: 4.12554213772474

我试图将数组中的每个数字四舍五入到最接近的整数。因此索引0 = 6,索引1 = 8,索引2 = 2,索引3 = 4。

我在计算结束时使用math.round方法,它对返回的数字没有任何影响,因为它们以上面显示的小数形式返回。

这是我的代码:

const Numerators = [];
    const Denominators = [];
    Array.forEach(({ DataValue }, i) => {
        const arrToPushTo = i % 2 === 0 ? Denominators : Numerators;
        arrToPushTo.push(Number(DataValue.replace(/,/g, '')));
    });
    const Percentage = Numerators.map((Numerator, i) => {
        const Denominator = Denominators[i];
        return 100 * Math.abs((Denominator - Numerator) / ((Denominator + Numerator) / 2));
        math.Round(Percentage)
    });

console.log(Percentage)

I have also tried creating another variable const Round = math.Round(Percentage) but when console logging this variable I am returned back with NaN

评论
  • sest
    sest 回复

    Just do Math.floor(val) or ~~val if you’re dealing with non-negative numbers

  • jquia
    jquia 回复

    math.Round doesn't mutate the original value. You need to assign the result to a variable or return it from a function. You want to move this out of the loop as well. Nothing after return in the loop will execute.

    就像是:

    const Percentage = Numerators.map((Numerator, i) => {
            const Denominator = Denominators[i];
            return 100 * Math.abs((Denominator - Numerator) / ((Denominator + Numerator) / 2));
        });
    
    const percentages = Percentage.map((percent) => math.Round(percent));
    
    console.log(percentages);
    

    编辑:我刚刚看到您已经有一个返回值。

    在一般的JavaScript代码样式上添加一些花絮:

    • TitleCased var names are generally reserved for constructors, that is functions that create objects, and classes. If you're using TypeScript, you'll see it for types and interfaces as well. The big picture is that title case is used for entities.
    • Array is a reserved word and cannot be used as a variable name. If you want to use Array.prototype.forEach, the syntax is [1,2,3,4].forEach((num) => doSomething(num))