一些常见的代码优化
//long
/***
if(x==='abc'||x ==='def'||x==='ghi'){
//logic
}**/
//short
/***
if(['abc','def','ghi'].includes(x)){
//logic
}**/
let test1 = undefined||null;
test2 = test1||"";
let test01 = "test01";
test02 = test01||"";
/**
* 聚合运算符
* ??是聚合运算符,
* 如果左值为null或undefined,
* 就返回右值,默认返回左值
* **/
const test03 = (null||undefined)??"default";
console.log(test03,"---03");
/***
* 多个变量赋值
* */
// let test04,test05,test06;
// test04 = 1;
// test05 = 2;
// test06 = 3;
let [test04,test05,test06] = [1,2,3];
/**
* 用于多个条件的与运算符
* **/
// if(test04){
// callMethod()
// }
// test04&&callMethod()
//比较结果的返回
// let compare;
// function checkReturn(){
// if(!(compare===undefined)){
// return compare
// }else{
// return callMe(compare)
// }
// }
// function checkReturn(){
// return compare||callMe(compare)
// }
/**
* 简短的函数调用语句
* **/
function shortFn(){
console.log('short1');
}
function shortFn2(){
console.log('short2');
}
let short1 = 1;
// if(short1 ===1){
// shortFn();
// }else{
// shortFn2();
// }
(short1===1?shortFn:shortFn2)();
/***
* switch对应缩写法
* **/
// switch(data){
// case 1:
// short1();
// break;
// case 2:
// short2();
// break;
// case 3:
// short3();
// break;
// }
// let switchData = {
// 1: short1(),
// 2: short2(),
// 3: short3()
// }
// switchData[something]&&switchData[something]()
/**
* 隐式返回缩写法
* **/
function calculate(dimeter){
return Math.PI*dimeter
}
//const calculate = dimeter =>Math.PI*dimeter
// or
//const calculate = dimeter =>(Math.PI*dimeter)
/***
* 延展操作符
* **/
//const yData = [1,2,3];
//const resultData = [1,2,3].concat(data);
const yData = [4,5,6];
const resultData = [...yData,1,2,3];
console.log(resultData)
//用于浅拷贝
const cloneData= [1,2,3];
const cloneData2 = cloneData.slice();
console.log(cloneData2,"---clone");
const cloneData3 = [...cloneData]
console.log(cloneData3,"---clone")
/**
* Array.find缩写法
* **/
const data = [{
type: 'test1',
name: 'abc'
},
{
type: 'test2',
name: 'cde'
},
{
type: 'test1',
name: 'fgh'
},
];
function findtest1(name) {
for (let i = 0; i < data.length; ++i) {
if (data[i].type === 'test1' && data[i].name === name) {
return data[i];
}
}
}
const filteredData = data.find(data => data.type === 'test1' && data.name === 'fgh');
console.log(filteredData,"---find");
/**
* 按位非和indexOf缩写法
* **/
// if(arr.indexOf(item)>-1) find
// if(arr.indexOf(item) ===-1) not find
// if(~arr.indexOf(item)) find
// if(!~arr.indexOf(item))not find
/**
* 对除 -1 外的任何数进行 按位非(~) 运算都会返回真值。把按位非的结果再次进行逻辑取反就是 !~,这非常简单。或者我们也可以使用 includes() 函数:
*
*/
// if(arr.includes(item)) true find
//(两个按位非运算符只适用于 32 位整型)
//向下取整去掉小数部分
Math.floor(1.9)===1 //true
~~1.9 ===1 //true
// var b = 2.33 | 0 ----> 2
// var c = 2.33 >> 0 ----> 2
//一个字符串重复多次
let str = "";
for(let i =0 ;i<5;i++){
str+='test'
}
console.log(str);//test test test test test
'test'.repeat(5)//同上
//找出数组中最大值
const arr1 = [1,2,3];
Math.max(...arr1);//3
Math.min(...arr1);//1
//幂运算
Math.pow(2,3);//8
console.log(2**3);//8
/**
* 金钱格式化
*
* **/
// 1、使用正则实现
// var test1 = '1234567890'
// var format = test1.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
// console.log(format) // 1,234,567,890
// 2、使用操作
// function formatCash(str) {
// return str.split('').reverse().reduce((prev, next, index) => {
// return ((index % 3) ? next : (next + ',')) + prev
// })
// }
// console.log(format)
/**
*
* #### 1. 生成随机ID
````
// 生成长度为10的随机字母数字字符串
Math.random().toString(36).substring(2);
````
#### 2. 每秒更新当前时间
````
setInterval(()=>document.body.innerHTML=new Date().toLocaleString().slice(10,18))
````
#### 3. 生成随机 16 进制 颜色 码 如 # ffffff
````
'#' + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, '0');
*
* **/
/**
* 按钮点击事件
* @param {number} status 活动状态:1开票中 2开票失败 3 开票成功 4 商品售罄 5 有库存未开团
* @param {string} identity 身份标识:guest客态 master主态
*/
const onButtonClick = (status, identity) => {
if (identity == 'guest') {
if (status == 1) {
//函数处理
} else if (status == 2) {
//函数处理
} else if (status == 3) {
//函数处理
} else if (status == 4) {
//函数处理
} else if (status == 5) {
//函数处理
} else {
//函数处理
}
} else if (identity == 'master') {
if (status == 1) {
//函数处理
} else if (status == 2) {
//函数处理
} else if (status == 3) {
//函数处理
} else if (status == 4) {
//函数处理
} else if (status == 5) {
//函数处理
} else {
//函数处理
}
}
}
//改造后
//利用数组循环的特性,符合条件的逻辑都会被执行,那就可以同时执行公共逻辑和单独逻辑。
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 }],
['default', () => { functionC }],
//...
])
/**
* 按钮点击事件
* @param {string} identity 身份标识:guest客态 master主态
* @param {number} status 活动状态:1开票中 2开票失败 3 开票成功 4 商品售罄 5 有库存未开团
*/
const onButtonClick = (identity, status) => {
let action = actions.get(`${identity}_${status}`) || actions.get('default')
action.call(this)
}
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){
return comparativeTotles.get(val)
}
let getMap = map(1); //如果查找不到返回undefined
if(!getMap){
console.log('查找不到')
}else{
concaozuole.log('执行操作')
getMap()
}