编程风格

编程风格

  1. let取代var
  2. 尽量使用const(全局特别如此)
  3. 静态字符串不用双引号,使用单引号或者反引号。
  4. 使用数组对变量赋值或使用对象或函数返回多个值时,使用解构赋值,如:
const arr = [1, 2, 3, 4];
const [first, second] = arr;//first=1,second=2
//obj
const { firstName, lastName } = obj;
// good
function processInput(input) {
  return { left, right, top, bottom };
}
const { left, right } = processInput(input);
  1. 单行对象不以,结尾,多行对象要,对象尽量静态化,一旦定义,不随便加属性,一定要加使用Object.assign,尽量使用简洁方法。
// good
const a = { k1: v1, k2: v2 };
const b = {
  k1: v1,
  k2: v2,
};
// if reshape unavoidable
const a = {};
Object.assign(a, { x: 3 });
// good
const a = { x: null };
a.x = 3;
  1. 使用...来拷贝数组。
const itemsCopy = [...items]
//用Array.from将类数组转数组
  1. 立即执行函数,匿名函数写成箭头形式,使用箭头函数取代Function.prototype.bind,不复杂的函数使用箭头函数:
// best
const boundMethod = (...params) => method.apply(this, params);

// 配置项集中到一个对象
function divide(a, b, { option = false } = {}) {
}
//不要直接使用arguments变量,使用...进行转化
function concatenateAll(...args) {
  return args.join('');
}
// good
function handleThings(opts = {}) {
  // ...
}
  1. 使用实体对象用Object,只需要key:value时用Map
  2. 使用Class取代prototype.
  3. 使用import而不是require,使用export取代module.exports,只有一个输出值使用export default,不要同时使用export defaultexport,减少使用*通配符导入。默认输出函数时,首字母小写,对象首字母大写。
posted @ 2022-10-24 23:56  梦呓qwq  阅读(18)  评论(0编辑  收藏  举报