代码优化

173 阅读1分钟
  1. null undefined 空检查
// Longhand
if (test1 !== null || test1 !== undefined || test1 !== '') {
    let test2 = test1;
}
// Shorthand
let test2 = test1 || '';
  1. null值检查和分配默认值
let test1 = null;
let test2 = test1 || ''
  1. 将值分配给多个变量
//Longhand 
let test1, test2, test3;
test1 = 1;
test2 = 2;
test3 = 3;
//Shorthand 
let [test1, test2, test3] = [1, 2, 3];
  1. 多个条件 如果当判断条件为true,才调用函数。
// longhand
if(test1) {
  callback()
}
// shorthand
test1 && callback()
  1. 短函数的应用
// Longhand
function test1() {
  console.log('test1')
 }
 function test2() {
  console.log('test2')
 }
 let test3 = 1;
 if(test3 === 1) {
   test1()
  } else {
    test2()
  }
  // Shorthand
  (test3 === 1 ? test1 : test2) ()
  1. switch简写
// Longhad
switch(data){
  case: 1:
    test1()
    break;
  case: 2:
    test2()
    break;
  case: 3:
    test3()
    break;
}
// Shorthand
let data= {
  1: test1,
  2: test2,
  3: test3
do[something] && data[something]()
  1. 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];
    } 
 }
}
// 简写
let  findata = data.find( item =〉 item.type === 'test1' && item.name === 'xq')
  1. Object.entries()
#将对象转成函数。
const obj = { foo: 'bar', baz: 42 };
console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]
  1. 如果有多个条件,可以在数组中存储多个值,使用数组includes()
  //Longhand 
 if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') { //logic }
  //Shorthand
 if(['abc', 'def', 'ghi'].includes(x)) {
 
 }