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 = {}) {
}
相关推荐
小白变怪兽1 小时前
一、react18+项目初始化(vite)
前端·react.js
ai小鬼头1 小时前
AIStarter如何快速部署Stable Diffusion?**新手也能轻松上手的AI绘图
前端·后端·github
墨菲安全2 小时前
NPM组件 betsson 等窃取主机敏感信息
前端·npm·node.js·软件供应链安全·主机信息窃取·npm组件投毒
GISer_Jing2 小时前
Monorepo+Pnpm+Turborepo
前端·javascript·ecmascript
天涯学馆2 小时前
前端开发也能用 WebAssembly?这些场景超实用!
前端·javascript·面试
我在北京coding3 小时前
TypeError: Cannot read properties of undefined (reading ‘queryComponents‘)
前端·javascript·vue.js
前端开发与ui设计的老司机3 小时前
UI前端与数字孪生结合实践探索:智慧物流的货物追踪与配送优化
前端·ui
全能打工人4 小时前
前端查询条件加密传输方案(SM2加解密)
前端·sm2前端加密
海天胜景4 小时前
vue3 获取选中的el-table行数据
javascript·vue.js·elementui