Coding Tips

113 阅读1分钟

提前返回 return

// good
function getData(type) {
  if (!data) return '';
}

// bad
function getData(type) {
  if (data) {
    // ...
  } else {
    // ...
  }
}

常量封装

export const SUBSCRIBE_STATUS_LIST = [
  {
    value: 'Y',
    name: '已通过'
  },
  {
    value: 'N',
    name: '已拒绝'
  },
  {
    value: '0',
    name: '待审核'
  }
];

export const TIME_UNIT_MAP = {
  'd': 'DAY',
  'm': 'MONTH',
  'h': 'HOUR'
}

使用 includes()

// good
const array = 
  ['path1', 'path2', 'path3'];
if (array.includes(path)) {
  // ...
}

// bad
if (path === 'path1' ||
    path === 'path2' || 
    path === 'path3') {
  // ...
}

真值判断简写

// Longhand
if (tmp === true) or if (tmp !== "") or if (tmp !== null)

// Shorthand 
// it will check empty string,null and undefined too
if (test1)

多条件的 && 运算符

// Longhand
if (test1) {
 callMethod();
}

// Shorthand
test1 && callMethod();

三目运算符实现短函数调用

// Longhand
function test1() {
  console.log('test1');
};
function test2() {
  console.log('test2');
};
var test3 = 1;
if (test3 == 1) {
  test1();
} else {
  test2();
}

// Shorthand
(test3 === 1? test1:test2)();

对象属性解构简写

let test1 = 'a';
let test2 = 'b';

//Longhand
let obj = {test1: test1, test2: test2};

//Shorthand
let obj = {test1, test2};

String 强制转换 Number

'12' * 1 // 12
+'12' // 12

+'1a' // NaN

奇偶数判断

!!(3 & 1) // true
!!(4 & 1) // false