js书写规范

参考文献:https://github.com/airbnb/javascript

1. 使用 const 与 let 代替 var (const / let)

  1.1、常量使用 const 定义,避免使用 var 定义:这样可以确保无法重新分配,这可能导致错误并难以理解代码。

// bad
var a = 1;
var b = 2;

// good
const a = 1;
const b = 2;

  1.2、使用 let 代替 var 定义变量:let是像var这样的块作用域而不是函数作用域。

// bad
var count = 1;
if (true) {
  count += 1;
}

// good, use the let.
let count = 1;
if (true) {
  count += 1;
}

  注意: let 和 const 都是块作用域

2. 对象(Object)

  2.1 使用文字形式创建对象

// bad
const item = new Object();

// good
const item = {};

  2.2、使用对象方法的简写

// bad
const atom = {
  value: 1,

  addValue: function (value) {
    return atom.value + value;
  },
};

// good
const atom = {
  value: 1,

  addValue(value) {
    return atom.value + value;
  },
};

  2.3、使用属性速记:因为简短而具有描述性

const lukeSkywalker = 'Luke Skywalker';

// bad
const obj = {
  lukeSkywalker: lukeSkywalker,
};

// good
const obj = {
  lukeSkywalker,
};

  2.4:、在对象声明的开头对速记属性进行分组。

const anakinSkywalker = 'Anakin Skywalker';
const lukeSkywalker = 'Luke Skywalker';

// bad
const obj = {
  episodeOne: 1,
  twoJediWalkIntoACantina: 2,
  lukeSkywalker,
  episodeThree: 3,
  mayTheFourth: 4,
  anakinSkywalker,
};

// good
const obj = {
 // 速记属性统一放前面或者后面 lukeSkywalker, anakinSkywalker, episodeOne:
1, twoJediWalkIntoACantina: 2, episodeThree: 3, mayTheFourth: 4, };

  2.5、仅引用无效标识符的属性:更容易阅读,因为他改善了语法突出显示的功能,并且还易于通过许多JS引擎进行优化。

// bad
const bad = {
  'foo': 3,
  'bar': 4,
  'data-blah': 5,
};

// good
const good = {
  foo: 3,
  bar: 4,
  'data-blah': 5,
};

3. 数组(Arrays)

  3.1、应尽量使用文字语法创建数组(如果有必要,特殊情况除外,如:new Array(10).fill(true))

// bad
const items = new Array();

// good
const items = [];

  3.2、使用 spread(‘...’)操作符copy数组

// bad
const len = items.length;
const itemsCopy = [];
let i;

for (i = 0; i < len; i += 1) {
  itemsCopy[i] = items[i];
}

// good
const itemsCopy = [...items];

  3.3、使用 spreads(‘...’)操作符将可迭代的对象转化为数组,而不是使用 Array.from([])

const foo = document.querySelectorAll('.foo');

// good
const nodes = Array.from(foo);

// best
const nodes = [...foo];

  3.4、Array.from 用于将类似数组的对象转换为数组

const arrLike = { 0: 'foo', 1: 'bar', 2: 'baz', length: 3 };

// bad
const arr = Array.prototype.slice.call(arrLike);

// good
const arr = Array.from(arrLike);

  3.5、使用 Array.from 而不是spread ...来映射可迭代对象,因为它避免了创建中间数组。

// bad
const baz = [...foo].map(bar);

// good
const baz = Array.from(foo, bar);

  3.6、如果数组有多行,则在打开和关闭数组括号之前使用换行符(因为一行的宽度是有限的,而数列的高度是无限的,这样有利于代码的阅读)

// bad
const arr = [
  [0, 1], [2, 3], [4, 5],
];

const objectInArray = [{
  id: 1,
}, {
  id: 2,
}];

const numberInArray = [
  1, 2,
];

// good
const arr = [[0, 1], [2, 3], [4, 5]];

const objectInArray = [
  {
    id: 1,
  },
  {
    id: 2,
  },
];

const numberInArray = [
  1,
  2,
];

 未完待续....

  

猜你喜欢

转载自www.cnblogs.com/jingxuan-li/p/12343922.html