试图锻炼如何处理阵列

时间:2014-08-31 02:50:22

标签: javascript arrays function object

我正在自学javascript的过程中看起来虽然我遇到了障碍。作为练习,我正在尝试建立一个税收计算器。

这是我构建的一个包含税号的对象:

var taxBracket = [
{bracket: 1, from:0, to:18200, percentage :0, amount:0},
{bracket: 2, from:18201, to:37000, percentage :19, over:18200, amount:0},
{bracket: 3, from:37001, to:80000, percentage :32.5, over:37000, amount:3752},
{bracket: 4, from:80001, to:180000, percentage :37, over:80000, amount:17547},
{bracket: 5, from:180001, to:0, percentage :45, over:180000, amount:54547}];

这是循环遍历对象以找到y的相应税率的函数

function returnTax (y){
    for(var x in taxBracket){
    if (y >= taxBracket[x].from && y <= taxBracket[x].to){
        var z = taxBracket[x].amount + ((grossIncome-taxBracket[x].over) * (taxBracket[x].percentage/100));
        return z;   
    }
};

问题是,如果y超过180000,则错误输出to为0.这是否只是解决了这个重复if语句功能的else语句?谢谢你的帮助!

4 个答案:

答案 0 :(得分:3)

到目前为止工作还不错。简单地使用Infinity而不是在最后一个支架上默认为0将修复它。我也就你的语法提出了一些建议,希望它有所帮助。

var taxBracket = [
    {bracket: 1, from: 0, to: 18200, percentage: 0, amount: 0},
    {bracket: 2, from: 18201, to: 37000, percentage: 19, over: 18200, amount: 0},
    {bracket: 3, from: 37001, to: 80000, percentage: 32.5, over: 37000, amount: 3752},
    {bracket: 4, from: 80001, to: 180000, percentage: 37, over: 80000, amount: 17547},

    // Use Infinity instead of 0 for the "to" value of bracket 5
    {bracket: 5, from: 180001, to: Infinity, percentage: 45, over: 180000, amount: 54547}
];

// Variable names like 'x', 'y' and 'z' can cause problems with code readability.
// Descriptive names such as "income", or even "string" or "int" will help you out when you come to review your code later!
function returnTax(y){

    // Using for..in with arrays can cause issues with enumerating over object properties.
    // You don't have to worry about it in this case, but a standard for loop (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for) is better practice.
    for(var x = 0; x < taxBracket.length; x++){

        if(y <= taxBracket[x].to){

            // I find breaking up long calculations into separate variables can make it
            // more readable. More preference than anything else though!
            var amountOver = grossIncome - taxBracket[x].over;
            var percent = taxBracket[x].percentage / 100;
            return taxBracket[x].amount + (amountOver * percent);

        }

    }

}

答案 1 :(得分:2)

您正在创建对象文字的数组文字。您应该使用标准for循环遍历数组。

答案 2 :(得分:1)

一种解决方案是将最后一个“to”字段设置为非常大的数字。

答案 3 :(得分:0)

你可以使用内置函数来循环对象数组,如

yourArray.forEach
( function (arrayItem)
{
var x =
arrayItem.prop1 + 2;
alert(x);
 });