简体   繁体   English

优化我的Javascript百分比计算器

[英]Optimise my Javascript percentage calculator

I have a javascript that calculates the percentage from two fields (retail and network) and then dumps that percentage into another field (markup). 我有一个JavaScript,可以从两个字段(零售和网络)计算百分比,然后将该百分比转储到另一个字段(标记)中。

As I am relatively new to the world of JS I have ended up reusing the code for several rows of fields. 由于我对JS领域比较陌生,因此我最终将代码重新用于几行字段。 This goes against DRY and KISS principles so I was wondering if you could give me some input on how to optimise my code so that it can handle any two fields and then dump a value to a third field. 这违背了DRY和KISS原则,所以我想知道您是否可以就如何优化我的代码给我一些意见,以便它可以处理任何两个字段,然后将值转储到第三个字段。

Here is a screenshot of my form segment that is using it. 这是正在使用它的表单段的屏幕截图。

http://i.imgur.com/FHvDs.png http://i.imgur.com/FHvDs.png

在此处输入图片说明

Here is my code I am using, I have had to reuse it four times and place the code in four functions eg (percentage1, percentage2, percentage3, percentage4) each one of these functions deals with a row of fields show in the screenshot. 这是我正在使用的代码,我不得不重复使用四次并将代码放置在四个函数中,例如(percentage1,percent2,percent3,percent4),这些函数中的每一个都处理屏幕快照中显示的一行字段。

    function percentage1()
                {


                //the dividee
                x = document.getElementById('tariff_data');
                //the divider
                y = document.getElementById('network_data');

                    //if the first value is lower than the second, append a "-" sign
                    if (x.value < y.value)
                    {
                        z = "-"+(x.value/y.value)*100;
                        document.getElementById('markup_data').value = z;
                    }
                    //not a negative percentage
                    else
                    {
                        z = (x.value/y.value)*100;
                        document.getElementById('markup_data').value = z;


                    }

                }   
function percentage2()
                {


                //the dividee
                x = document.getElementById('tariff_rental');
                //the divider
                y = document.getElementById('network_rental');

                    //if the first value is lower than the second, append a "-" sign
                    if (x.value < y.value)
                    {
                        z = "-"+(x.value/y.value)*100;
                        document.getElementById('markup_rental').value = z;
                    }
                    //not a negative percentage
                    else
                    {
                        z = (x.value/y.value)*100;
                        document.getElementById('markup_data').value = z;


                    }

                }
etc etc.... 

These functions are called using the onchange HTML attribute 这些函数使用onchange HTML属性调用

Also when I divide by a decimal number it gives the wrong value, any Ideas how to make it calculate the correct percentage of a decimal number? 另外,当我用十进制数除以错误的值时,是否有任何想法如何使它计算出正确的十进制数百分比?

My code also gives out these strange outputs: 我的代码还给出了这些奇怪的输出:

NaN , Infinity 无限大

Thanks 谢谢

Rather than optimization, let's focus on correctness first =) 除了优化之外,我们先关注正确性=)

Note that the HTMLInputElement.value property has type "string", so your arithmetic operators are doing implicit type conversion which means you are likely often doing string concatenation instead of the numeric operations you expect. 请注意, HTMLInputElement.value属性的类型为“字符串”,因此您的算术运算符正在执行隐式类型转换,这意味着您可能经常会进行字符串连接,而不是期望的数字运算。

I strongly recommend explicitly converting them to numbers first and checking for invalid input, also, don't forget to declare your variables first using var so they don't potentially clobber globals, eg: 我强烈建议您先将它们明确转换为数字,然后检查输入是否无效,也不要忘记先使用var声明变量,这样它们就不会破坏全局变量,例如:

var x = Number(document.getElementById('tariff_data'));
var y = Number(document.getElementById('network_data'));
if (!isFinite(x) || !isFinite(y)) {
  // Handle non-numerical input...
}

You can also use the parseFloat function if you prefer, eg: 如果愿意,还可以使用parseFloat函数,例如:

var x = parseFloat(document.getElementById('tariff_data'), 10);

I highly recommend doing some formal learning about the JavaScript language; 我强烈建议您对JavaScript语言进行一些正式学习; it is full of pitfalls but if you stick to the "good parts" you can save yourself a lot of hassle and headache. 它充满了陷阱,但是如果您坚持“良好的部分” ,则可以为自己省去很多麻烦和头痛。

With regard to DRYing your code out; 关于将您的代码干燥; remember that you can: 请记住,您可以:

  • Pass parameters to your functions and use those arguments within the function 将参数传递给函数并在函数中使用这些参数
  • Return values using the return keyword 使用return关键字返回值

In your case, you've got all your multiplication code repeated. 就您而言,您已经重复了所有乘法代码。 While trying to fix the string vs. number problems maerics has already mentioned, you could do something like this: 在尝试解决maerics提到的字符串与数字问题时,您可以执行以下操作:

// We're assuming 'dividee' and 'divider' are numbers.
function calculatePercentage(dividee, divider) {
    var result;

    // Regardless of the positive/negative result of the calculation,
    // get the positive result using Math.abs().
    result = Math.abs((dividee.value / divider.value) * 100);

    // If the result was going to be negative...
    if (dividee.value < divider.value) {
        // Convert our result to negative.
        result = result * -1;
    }

    // Return our result.
    return result;
}

Then, in your percentage functions, you can just call this code like so: 然后,在百分比函数中,您可以像下面这样调用此代码:

function percentage1() {
    var tariff, network, markup;

    tariff = parseFloat(document.getElementById('tariff_data').value, 10);
    network = parseFloat(document.getElementById('network_data').value, 10);
    markup = document.getElementById('markup_data');

    markup.value = calculatePercentage(tariff, network);
}

Obviously, you could take this further, and create a function which takes in the IDs, extracts the values from the elements etc., but you should try and build that yourself based on these tips. 显然,您可以更进一步,并创建一个接受ID,从元素中提取值等的函数,但是您应该尝试根据这些技巧自行构建。

Maerics also makes a very good point which you should take note of; Maerics还提出了一个很好的观点,您应该注意这一点; learn more about the Good Parts of JavaScript. 了解有关JavaScript优秀部分的更多信息。 Douglas Crockford's book is excellent, and should be read and understood by all JS developers, IMHO. Douglas Crockford的书非常出色,所有JS开发人员IMHO都应阅读并理解。

Hope this helps you clean your code up! 希望这可以帮助您清理代码!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM