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 = {}) {
}
相关推荐
2601_951615208 分钟前
网站模板 网站网页模板下载
前端·网络·html
酷炫码神42 分钟前
Day 1|HTML5:一个商城首页的骨架,从 DOCTYPE 到语义化
前端·html·html5
AI源码1 小时前
鲜花商城(HTML 版)
前端·html
hiahiahia1231 小时前
Message 和对话
服务器·前端·数据库
溪语流沙2 小时前
【Web全栈进阶】Composition API与组件通信:props深入、emit、插槽
前端·css·vue.js
ZoeLandia2 小时前
TypeScript 03:泛型与工具类型
前端·typescript
code_Bo2 小时前
从策划到上线:我和 AI 一起做了个微信记账小程序
前端·ai编程·cursor
Shirley~~2 小时前
Three.js加载Gltf模型并播放动画
前端·3d
Data analyse4562 小时前
Session超时与浏览器休眠的计时校验
大数据·前端·数据库·数据分析
星始流年2 小时前
AI 时代,软件程序员未来 10—15 年的职业前景
前端·后端·ai编程