Page 44 - 你不知道的JavaScript(下卷)
P. 44

通常来说,函数是可以通过名字被“调用”的已命名代码段,每次调用,其中的代码就会
                 运行。考虑:

                     function printAmount() {
                         console.log( amount.toFixed( 2 ) );
                     }

                     var amount = 99.99;

                     printAmount(); // "99.99"

                     amount = amount * 2;

                     printAmount(); // "199.98"
                 函数可以接受参数,即你传入的值,也可以返回一个值:

                     function printAmount(amt) {
                         console.log( amt.toFixed( 2 ) );
                     }

                     function formatAmount() {
                         return "$" + amount.toFixed( 2 );
                     }

                     var amount = 99.99;

                     printAmount( amount * 2 );   // "199.98"

                     amount = formatAmount();
                     console.log( amount );    // "$99.99"

                 函数 printAmount(..) 接受一个名为 amt 的参数。函数 formatAmount() 返回一个值。你也
                 可以在同一个函数中同时使用这两种技术。

                 通常来说,你会在计划多次调用的代码上使用函数,但只是将相关的代码组织到一起成为
                 命名集合也是很有用的,即使只准备调用一次。

                 考虑:

                     const TAX_RATE = 0.08;

                     function calculateFinalPurchaseAmount(amt) {
                         // 根据税费来计算新的数值
                         amt = amt + (amt * TAX_RATE);

                         // 返回新的数值
                         return amt;
                     }

                     var amount = 99.99;


                                                                              深入编程   |   21

                                图灵社区会员 avilang(1985945885@qq.com) 专享 尊重版权
   39   40   41   42   43   44   45   46   47   48   49