switch..case使用
2024-08-28 22:13:47
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
最新文章
- javascript正则表达式
- FusionCharts的使用方法(php)
- kuangbin_ShortPath H (POJ 3660)
- return遇到finally
- 使用DataList 分页方法
- Android开源项目 Universal imageloader 源码研究之项目框架
- 转:pthread_detach()函数
- HBase的基本操作
- 1572: [Usaco2009 Open]工作安排Job
- C++基础算法学习——熄灯问题
- 【使用指南】WijmoJS 前端开发工具包
- 冒烟测试(smoke testing)
- android studio 3.0 安装配置
- nexage video asset tag
- leetcode--539. Minimum Time Difference
- cocos2d 特效
- BZOJ3560 DZY Loves Math V(欧拉函数)
- python学习之路 六 :装饰器
- threading模块、ThreadLocal
- google浏览器:Ignored call to 'confirm()'. The document is sandboxed, and the 'allow-modals' keyword is not set
热门文章
- C#微信公众号开发系列教程三(消息体签名及加解密)
- 怎样在Windows资源管理器中添加右键菜单以及修改右键菜单顺序
- 【Android】设置android:maxLines=";1";后,android:imeOptions=";actionSearch";失效
- NodeJS+Express下构建后端MVC文件结构
- 导入excel
- Windows HTTP Services
- windows下webstorm开发react-native智能提示
- 求两个数字的最大公约数-Python实现,三种方法效率比较,包含质数打印质数的方法
- javascript 核心语言笔记 6 - 对象
- C++开始前篇,深入编译链接