ES6代码规范(整理)

来源:互联网 发布:淘宝宝贝被同行举报 编辑:程序博客网 时间:2024/05/29 07:00

ES6提出了两个新的声明变量的命令:let 和 const
1. 建议不再使用var,而使用let 和const 。优先使用const。

//badvar a = 1, b =2 , c = 3;// goodconst [a,b,c] = [1,2,3];

2.静态字符串一律使用单引号或反引号,不建议使用双引号。动态字符使用反引号。

//bad  const a = "foobar"; const b = 'foo'+a+'bb';// good const a = 'foobar';const b = `foo${a}bar`;

3.优先使用解构赋值

const arr = [1, 2, 3, 4];// badconst first = arr[0];const second = arr[1];// goodconst [first, second] = arr;

函数的参数如果是对象的成员,优先使用解构赋值。

// badfunction getFullName(user) {  const firstName = user.firstName;  const lastName = user.lastName;}// goodfunction getFullName(obj) {  const { firstName, lastName } = obj;}// bestfunction getFullName({ firstName, lastName }) {}

如果函数返回多个值,优先使用对象的解构赋值,而不是数组的解构赋值。这样便于以后添加返回值,以及更改返回值的顺序。

// badfunction processInput(input) {  return [left, right, top, bottom];}// goodfunction processInput(input) {  return { left, right, top, bottom };}const { left, right } = processInput(input);

5.对象的属性和方法尽量采用简洁表达法,这样易于描述和书写

// bad var ref = 'some value';const atom = {  ref:ref,  value:1,  addValue:function(value){    return atom.value + value;  },}//  good const atom = {  ref,  value:1,  addValue(value){    return atom.value + value;  }}

使用扩展运算符(…) 复制数组,使用Array.from 方法将类似数组的对象转为数组。

不在使用arguments (伪数组) 而是用…rest 运算符(真数组)。

学习链接:
Airbnb前端规范

阿里员工前端规范

es6参考标准

0 0