ES6-代码编程风格(数组、函数)

1 数组

使用扩展运算符(...)复制数组。

const itemsCopy  = [...items];

使用Array.from 方法将类似数组的对象转为数组。

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

const nodes = Array.from(foo);

2 函数

立即执行函数可以写成箭头函数的形式。

(() => {
  console.log('Welcome to the Internet.');
})();

那些需要使用函数表达式的场合,尽量用箭头函数提代。因为这员工更简洁,而且绑定了this.

//bad
[1, 2, 3].map(function (x) {
  return x*x;
});
//good
[1, 2, 3].map((x) => {
  return x*x;
});
//best
[1, 2, 3].map(x => x*x);

简单的、单行的、不会复用的函数,建议采用箭头函数。 如果函数体较为复杂,行数较多,韩式应该采用传统的函数写法。

所有的配置项都应该集中在一个对象,放在最后一个参数, 布尔值不可以直接作为参数。

// bad
function divide(a, b, {option = false}) {}
// good
function divide(a, b, { option = false } = {}) {}

不要在函数体内使用arguments变量, 使用rest运算符(...)代替。 

//bad
function concatenateAll () {
  const args = Array.prototype.slice.call(arguments); 
  return args.join('');
}
//good
function concatenateAll(...args) {
  return args.join('')
}

使用默认值语法设置函数参数的默认值。

//bad
function handleThings(opts) {
  opts = opts || {};
}
//good 
function handleThings(opts = {}) {
}

你可能感兴趣的:(es6,前端,javascript)