javaScript的基本优雅写法
1.判断为空
小白:
if(a == undefined) a = []; if(params.success){ params.success(res); }
优雅:
a = a || [];
params.success&¶ms.success(res);
2.多条件判断
小白:
var Statistics = function() { console.log('执行') } switch (currentTab){ case 0: Statistics(); break; case 1: Statistics(); break; case 2: Statistics(); break; case 3: Statistics(); break; }
优雅:
var Statistics = function () { console.log('执行') } const comparativeTotles = new Map([ [0,Statistics], [1,Statistics], [2,Statistics], [3,Statistics] ]) let map = function(val: any){ return comparativeTotles.get(val) } let getMap = map(4) if(!getMap){ console.log('差找不到') }else{ console.log('执行操作') getMap() }
3.if else
小白:
const onButtonClick = (status: any, identity: any) => { if (identity == 'guest') { if (status == 1) { console.log('do something') } else if (status == 2) { console.log('do something') } else if (status == 3) { console.log('do something') } else if (status == 4) { console.log('do something') } else { console.log('do something') } } else if (identity == 'master') { if (status == 1) { console.log('do something') } else if (status == 2) { console.log('do something') } else if (status == 3) { console.log('do something') } else if (status == 4) { console.log('do something') } else { console.log('do something') } } }
优雅:
const functionA = () => { /*do sth*/} const functionB = () => { /*do sth*/} const functionC = () => { /*send log*/} const actions = new Map([ ['guest_1', () => { functionA }], ['guest_2', () => { functionB }], ['guest_3', () => { functionC }], ['guest_4', () => { functionA }], ]) const onButtonClick = (identity, status) => { let action = actions.get(`${identity}_${status}`) || actions.get('default') action.call(this) }
4.一些场景
//生成随机ID Math.random().toString(36).substring(2); //金钱格式化 var test1 = '1234567890' var format = test1.replace(/\B(?=(\d{3})+(?!\d))/g, ',') function formatCash(str) { return str.split('').reverse().reduce((prev, next, index) => { return ((index % 3) ? next : (next + ',')) + prev }) }