【JS技巧】JavaScript技巧介绍1 -- switch

来源:互联网 发布:程序员有转行的吗 编辑:程序博客网 时间:2024/05/17 13:12

switch


1 switch条件为数字时,可以使用数组map


var fun0 = function(){console.log('fun0');}var fun1 = function(){console.log('fun1');}var fun2 = function(){console.log('fun2');}var condition = 1;switch(condition){case 0:fun0();break;case 1:fun1();break;case 2:fun2();break;}


等同于


var fun0 = function(){console.log('fun0');}var fun1 = function(){console.log('fun1');}var fun2 = function(){console.log('fun2');}var condition = 1;var condition_arr_map = [fun0, fun1, fun2];condition_arr_map[condition]();


2 当switch条件为字符串时,可以使用object的key和value来做map


var fun0 = function(){console.log('fun0');}var fun1 = function(){console.log('fun1');}var fun2 = function(){console.log('fun2');}var fruit_kind = 'grape';switch(fruit_kind){case 'apple':fun0();break;case 'banana':fun1();break;case 'grape':fun2();break;}


等同于



var fun0 = function(){console.log('fun0');}var fun1 = function(){console.log('fun1');}var fun2 = function(){console.log('fun2');}var fruit_kind = 'grape';var condition_obj_map = {'apple': fun0,'banana': fun1,'grape': fun2}condition_obj_map[fruit_kind]();


0 0
原创粉丝点击