所得税の計算のような、入力値によって段階的に処理が変わる処理についての話です。
一応、何も考えずに実装したら以下のようなコードになりました。が、
・if文だらけ
・「税率・控除額・所得金額の範囲」は、しばしば変更される「データ」と言え、処理とデータが混在している状態である
ので、もっといい書き方がないかと思っています。
このような処理でのエレガントな書き方についてです。下記のコードは「ベスト」でしょうか?もっといい書き方がありますでしょうか?あなたならどう書きますか?
よろしくお願いします。
lang
1<!DOCTYPE html> 2<html lang="ja"> 3<head> 4 <meta charset="utf-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1"> 6 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 7</head> 8<body> 9 10所得<input type="text" id="input">円 11<input type="button" id="btn" value="算出"><br> 12税額<input type="text" id="result">円 13 14<script> 15jQuery(function ($) { 16 17 function calcTax(income) { 18 if (income == "" || isNaN(income) || income < 0) { 19 return ""; 20 } 21 var taxRate, deduction; 22 if (income <= 1950000) { 23 taxRate = 0.05, deduction = 0; 24 } else if (income <= 3300000) { 25 taxRate = 0.10, deduction = 97500; 26 } else if (income <= 6950000) { 27 taxRate = 0.20, deduction = 427500; 28 } else if (income <= 9000000) { 29 taxRate = 0.23, deduction = 636000; 30 } else if (income <= 18000000) { 31 taxRate = 0.33, deduction = 1536000; 32 } else if (income <= 40000000) { 33 taxRate = 0.40, deduction = 2796000; 34 } else { 35 taxRate = 0.45, deduction = 4796000; 36 } 37 return (income - deduction) * taxRate; 38 } 39 40 $("#btn").click(function() { 41 $("#result").val(calcTax($("#input").val())); 42 }); 43}); 44</script> 45 46</body> 47</html>
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/02/15 08:16