加入收藏 | 设为首页 | 会员中心 | 我要投稿 湖南网 (https://www.hunanwang.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 教程 > 正文

你试过不消if写代码吗?

发布时间:2018-04-18 11:30:51 所属栏目:教程 来源:站长网
导读:译者按:试着不消 if 写代码,是件很风趣的事,并且,万一你了解了什么是数据即代码,代码即数据呢? 我在教刑孤枢程时,喜好给他们一些小小的挑衅,好比:不行使if语句(可能三元运算符、switch语句等)办理一些编程题目。 这样做有什么意义吗? 究竟上,它可

不消switch

  1. const doubler = (input) => { 
  2.   return doubler.operationsByType[typeof input](input); 
  3. }; 
  4.  
  5. doubler.operationsByType = { 
  6.   number: (input) => input + input, 
  7.   string: (input) => 
  8.     input 
  9.       .split('') 
  10.       .map((letter) => letter + letter) 
  11.       .join(''), 
  12.   function: (input) => { 
  13.     input(); 
  14.     input(); 
  15.   }, 
  16.   object: (input) => { 
  17.     Object.keys(input) 
  18.           .map((key) => (input[key] = doubler(input[key]))); 
  19.     return input; 
  20.   }, 
  21. }; 

可知,我将每一种参数范例对应的操纵绑定到了doubler.operationsByType,这样不必要switch语句,就可以实现doubler函数了。

注:为了担保可读性,本文回收意译而非直译。其它,本文版权归原作者全部,翻译仅用于进修。

(编辑:湖南网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读