1、多个if...else连在一起使用的时候,可以转为使用更方便的switch结构。
switch (XXX) {
case "aaa":
// ...
break;
case "bbb":
// ...
break;
default:
// ...
}
需要注意的是,每个case代码块内部的break语句不能少,否则会接下去执行下一个case代码块,而不是跳出switch结构。

2、switch结构不利于代码重用,往往可以用对象形式重写
function getItemPricing(customer, item) {
switch(customer.type) {
case 'VIP':
return item.price * item.quantity * 0.50;
case 'Preferred':
return item.price * item.quantity * 0.75;
case 'Regular':
case default:
return item.price * item.quantity;
}
}

上面代码根据不同用户,返回不同的价格。你可以发现,switch语句包含的三种情况,内部逻辑都是相同的,不同只是折扣率。这启发我们可以用对象属性,重写这个判断。
var pricing = {
'VIP': 0.50,
'Preferred': 0.75,
'Regular': 1.0
}; function getItemPricing(customer, item) {
if (pricing[customer.type])
return item.price * item.quantity * pricing[customer.type];
else
return item.price * item.quantity * pricing.Regular;
}

如果价格档次再多一些,对象属性写法的简洁优势就更明显了。 PS:干前端一年,至今停留在简单的if..else和for循环。看到这个switch的基础讲解,觉得自己实在是太low了。这么久了,一点编程思想都没有养成呢。
参考网址:http://javascript.ruanyifeng.com/grammar/basic.html
 

最新文章

  1. javascript正则表达式
  2. FusionCharts的使用方法(php)
  3. kuangbin_ShortPath H (POJ 3660)
  4. return遇到finally
  5. 使用DataList 分页方法
  6. Android开源项目 Universal imageloader 源码研究之项目框架
  7. 转:pthread_detach()函数
  8. HBase的基本操作
  9. 1572: [Usaco2009 Open]工作安排Job
  10. C++基础算法学习——熄灯问题
  11. 【使用指南】WijmoJS 前端开发工具包
  12. 冒烟测试(smoke testing)
  13. android studio 3.0 安装配置
  14. nexage video asset tag
  15. leetcode--539. Minimum Time Difference
  16. cocos2d 特效
  17. BZOJ3560 DZY Loves Math V(欧拉函数)
  18. python学习之路 六 :装饰器
  19. threading模块、ThreadLocal
  20. google浏览器:Ignored call to 'confirm()'. The document is sandboxed, and the 'allow-modals' keyword is not set

热门文章

  1. C#微信公众号开发系列教程三(消息体签名及加解密)
  2. 怎样在Windows资源管理器中添加右键菜单以及修改右键菜单顺序
  3. 【Android】设置android:maxLines="1"后,android:imeOptions="actionSearch"失效
  4. NodeJS+Express下构建后端MVC文件结构
  5. 导入excel
  6. Windows HTTP Services
  7. windows下webstorm开发react-native智能提示
  8. 求两个数字的最大公约数-Python实现,三种方法效率比较,包含质数打印质数的方法
  9. javascript 核心语言笔记 6 - 对象
  10. C++开始前篇,深入编译链接