官术网_书友最值得收藏!

Autodetection formatting

Autodetection of the variable type, when passed into a function, is great for cleaner code. In your view, you could invoke the function and pass the one parameter you wish to format. For example:

      {{ format(person.balance) }}

The method would then contain a switch statement and format the variable based on the typeof value. A switch statement can evaluate a single expression and then execute different code based on the output. Switch statements can be very powerful as they allow clauses to be built up—utilizing several different bits of code based on the result. More can be read about switch statements on MDN. 

Switch statements are a great alternative to if statements if you are comparing the same expression. You are also able to have several cases for one block of code and even include a default if none of the previous cases was met. As an example of one in use, our format method might look like:

      format(variable) {
switch (typeof variable) {
case 'string':
// Formatting if the variable is a string
break;
case 'number':
// Number formatting
break;
default:
// Default formatting
break;
}
}

The important thing to note is the break; lines. These finish each switch case. If a break was omitted, the code would carry on and execute the following case—which sometimes is the desired effect.

Autodetecting the variable type and formatting is a great way of simplifying your code. However, for our app, it is not a suitable solution as we are formatting the date, which when outputting the typeof results in a string, and would not be identifiable from other strings we may wish to format.

主站蜘蛛池模板: 洞口县| 广平县| 诸城市| 永顺县| 丹江口市| 镇平县| 军事| 驻马店市| 台东市| 钟山县| 永定县| 阜平县| 新宾| 岳阳县| 麻栗坡县| 柘荣县| 大足县| 通辽市| 武宁县| 文登市| 陕西省| 丹东市| 吴江市| 临朐县| 滨海县| 博客| 涡阳县| 濮阳县| 厦门市| 沛县| 积石山| 武安市| 奈曼旗| 行唐县| 凉山| 泽普县| 岑巩县| 鹤峰县| 集贤县| 专栏| 苏尼特右旗|