js編碼習慣

ES6 中可以使用 array.includes(item) 來代替 array.indexOf(item) !== -1

 

判斷屬性是否存在

// 不好
const object = {
  prop: 'value'
};
if (object.nonExistingProp === undefined) {
  // ...
}

// 好
const object = {
  prop: 'value'
};
if ('nonExistingProp' in object) {
  // ...
}

對象的默認屬性

 

// 不好
function foo(options) {
  if (object.optionalProp1 === undefined) {
    object.optionalProp1 = 'Default value 1';
  }
  // ...
}

// 好
function foo(options) {
  const defaultProps = {
    optionalProp1: 'Default value 1'
  };
  options = {
    ...defaultProps,
    ...options
  }
}

默認函數參數

// 不好
function foo(param1, param2) {
  if (param2 === undefined) {
    param2 = 'Some default value';
  }
  // ...
}
// 好
function foo(param1, param2 = 'Some default value') {
  // ...
}

原文鏈接:https://dmitripavlutin.com/unlearn-javascript-bad-coding-habits/

中文鏈接:https://juejin.im/post/5d3e3706f265da1b60294c1f

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章