前面叁个参谋指南

前端参谋指南

2015/05/09 · CSS,
HTML5,
JavaScript ·
前端

本文由 伯乐在线 –
cucr
翻译,周进林
校稿。未经许可,禁绝转载!
法文出处:github.com。迎接出席翻译组。

HTML

语义

HTML5为大家提供了汪洋的语义成分,意在精准地陈诉内容。确认保障您收益于其丰硕的词汇。

XHTML

<!– bad –> <div id=”main”> <div class=”article”>
<div class=”header”> <h1>Blog post</h1>
<p>Published: <span>21st Feb, 2015</span></p>
</div> <p>…</p> </div> </div> <!– good
–> <main> <article> <header> <h1>Blog
post</h1> <p>Published: <time
datetime=”2015-02-21″>21st Feb, 2015</time></p>
</header> <p>…</p> </article> </main>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!– bad –>
<div id="main">
  <div class="article">
    <div class="header">
      <h1>Blog post</h1>
      <p>Published: <span>21st Feb, 2015</span></p>
    </div>
    <p>…</p>
  </div>
</div>
 
<!– good –>
<main>
  <article>
    <header>
      <h1>Blog post</h1>
      <p>Published: <time datetime="2015-02-21">21st Feb, 2015</time></p>
    </header>
    <p>…</p>
  </article>
</main>

确认保证您精晓你正在利用的语义成分。以错误的秘籍利用语义成分比不采用更不佳。

XHTML

<!– bad –> <h1> <figure> <img alt=Company
src=logo.png> </figure> </h1> <!– good –>
<h1> <img alt=Company src=logo.png> </h1>

1
2
3
4
5
6
7
8
9
10
11
<!– bad –>
<h1>
  <figure>
    <img alt=Company src=logo.png>
  </figure>
</h1>
 
<!– good –>
<h1>
  <img alt=Company src=logo.png>
</h1>

简洁

有限支撑代码简洁。忘记旧的XHTML习贯。

XHTML

<!– bad –> <!doctype html> <html lang=en>
<head> <meta http-equiv=Content-Type content=”text/html;
charset=utf-8″ /> <title>Contact</title> <link
rel=stylesheet href=style.css type=text/css /> </head>
<body> <h1>Contact me</h1> <label> Email
address: <input type=email placeholder=you@email.com
required=required /> </label> <script src=main.js
type=text/javascript></script> </body> </html>
<!– good –> <!doctype html> <html lang=en> <meta
charset=utf-8> <title>Contact</title> <link
rel=stylesheet href=style.css> <h1>Contact me</h1>
<label> Email address: <input type=email
placeholder=you@email.com required> </label> <script
src=main.js></script> </html>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<!– bad –>
<!doctype html>
<html lang=en>
  <head>
    <meta http-equiv=Content-Type content="text/html; charset=utf-8" />
    <title>Contact</title>
    <link rel=stylesheet href=style.css type=text/css />
  </head>
  <body>
    <h1>Contact me</h1>
    <label>
      Email address:
      <input type=email placeholder=you@email.com required=required />
    </label>
    <script src=main.js type=text/javascript></script>
  </body>
</html>
 
<!– good –>
<!doctype html>
<html lang=en>
  <meta charset=utf-8>
  <title>Contact</title>
  <link rel=stylesheet href=style.css>
 
  <h1>Contact me</h1>
  <label>
    Email address:
    <input type=email placeholder=you@email.com required>
  </label>
  <script src=main.js></script>
</html>

可访问性

可访谈性不应有是多个随后的主见。你不要成为壹人WCAG行家来进步你的网址,你能够即时早先修复那个不成难题,它将发出宏大的改革,如:

  • 学会科学利用alt属性
  • 确定保障您的链接和开关等都很好地方统一标准记(没有<div class
    =button>这种暴行)
  • 无须完全依附颜色来传达音讯
  • 显式地给表单控件加标签

XHTML

<!– bad –> <h1><img alt=”Logo”
src=”logo.png”></h1> <!– good –> <h1><img
alt=”My Company, Inc.” src=”logo.png”></h1>

1
2
3
4
5
<!– bad –>
<h1><img alt="Logo" src="logo.png"></h1>
 
<!– good –>
<h1><img alt="My Company, Inc." src="logo.png"></h1>

语言

固然定义语言和字符编码是可选的,但推荐在文书档案等第注脚它们,就算它们曾在HTTP乞求底部已经钦点。字符编码优用utf
– 8。

XHTML

<!– bad –> <!doctype html> <title>Hello,
world.</title> <!– good –> <!doctype html> <html
lang=en> <meta charset=utf-8> <title>Hello,
world.</title> </html>

1
2
3
4
5
6
7
8
9
10
<!– bad –>
<!doctype html>
<title>Hello, world.</title>
 
<!– good –>
<!doctype html>
<html lang=en>
  <meta charset=utf-8>
  <title>Hello, world.</title>
</html>

性能

除非有一个靠边的理由在内容前边加载脚本,不然请不要把它坐落眼前阻止页面包车型客车渲染。如若你的样式表相当的大,分离出初叶化时必须的体裁,并在三个独门样式表中延迟加载别的一些。三回HTTP央浼明显低于一回,但感知速度是最器重的因素。

XHTML

<!– bad –> <!doctype html> <meta charset=utf-8>
<script src=analytics.js></script> <title>Hello,
world.</title> <p>…</p> <!– good –>
<!doctype html> <meta charset=utf-8> <title>Hello,
world.</title> <p>…</p> <script
src=analytics.js></script>

1
2
3
4
5
6
7
8
9
10
11
12
13
<!– bad –>
<!doctype html>
<meta charset=utf-8>
<script src=analytics.js></script>
<title>Hello, world.</title>
<p>…</p>
 
<!– good –>
<!doctype html>
<meta charset=utf-8>
<title>Hello, world.</title>
<p>…</p>
<script src=analytics.js></script>

CSS

分号

本领上来说,分号在CSS里担纲三个分隔符,但请把它充作三个完毕符。

CSS

/* bad */ div { color: red } /* good */ div { color: red; }

1
2
3
4
5
6
7
8
9
/* bad */
div {
  color: red
}
 
/* good */
div {
  color: red;
}

盒模型

盒模型对全体文书档案应该是如出意气风发辙的。就算全局样式 * { box-sizing:border-box;}
很好,但毫无在特定成分退换默许的盒模型(假诺您能够幸免那样做卡塔尔国。

CSS

/* bad */ div { width: 100%; padding: 10px; box-sizing: border-box; }
/* good */ div { padding: 10px; }

1
2
3
4
5
6
7
8
9
10
11
/* bad */
div {
  width: 100%;
  padding: 10px;
  box-sizing: border-box;
}
 
/* good */
div {
  padding: 10px;
}

决不更改成分的默许行为(若是你可避防止那样做卡塔 尔(阿拉伯语:قطر‎。尽量保险成分在日常的文书档案流中。比如,删除图像下边包车型地铁空域,不应有改成其默许呈现:

CSS

/* bad */ img { display: block; } /* good */ img { vertical-align:
middle; }

1
2
3
4
5
6
7
8
9
/* bad */
img {
  display: block;
}
 
/* good */
img {
  vertical-align: middle;
}

如出风姿洒脱辙的,不要让二个因素脱离文书档案流(假设你能够幸免那样做卡塔尔。

CSS

/* bad */ div { width: 100px; position: absolute; right: 0; } /* good
*/ div { width: 100px; margin-left: auto; }

1
2
3
4
5
6
7
8
9
10
11
12
/* bad */
div {
  width: 100px;
  position: absolute;
  right: 0;
}
 
/* good */
div {
  width: 100px;
  margin-left: auto;
}

位置

有那么些主意能够在CSS中固定成分,但尝试约束本中国人民银行使上面包车型大巴习性/值。优先顺序如下:

XHTML

display: block; display: flex; position: relative; position: sticky;
position: absolute; position: fixed;

1
2
3
4
5
6
display: block;
display: flex;
position: relative;
position: sticky;
position: absolute;
position: fixed;

选择器

减去紧耦合的DOM选拔器。当您的选择器超越3个结构伪类、后代或兄弟的重新整合,考虑增添二个class到您须求极度的成分上。

CSS

/* bad */ div:first-of-type :last-child > p ~ * /* good */
div:first-of-type .info

1
2
3
4
5
/* bad */
div:first-of-type :last-child > p ~ *
 
/* good */
div:first-of-type .info

防止在不必要的时候重载你的选用器。

CSS

/* bad */ img[src$=svg], ul > li:first-child { opacity: 0; } /*
good */ [src$=svg], ul > :first-child { opacity: 0; }

1
2
3
4
5
6
7
8
9
/* bad */
img[src$=svg], ul > li:first-child {
  opacity: 0;
}
 
/* good */
[src$=svg], ul > :first-child {
  opacity: 0;
}

特性

决不让选择器难以隐瞒。裁减使用 id 和幸免 !important。

CSS

/* bad */ .bar { color: green !important; } .foo { color: red; } /*
good */ .foo.bar { color: green; } .foo { color: red; }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/* bad */
.bar {
  color: green !important;
}
.foo {
  color: red;
}
 
/* good */
.foo.bar {
  color: green;
}
.foo {
  color: red;
}

覆盖

蒙面样式让接收器和调治变得没有错使用。尽或许制止它。

CSS

/* bad */ li { visibility: hidden; } li:first-child { visibility:
visible; } /* good */ li + li { visibility: hidden; }

1
2
3
4
5
6
7
8
9
10
11
12
/* bad */
li {
  visibility: hidden;
}
li:first-child {
  visibility: visible;
}
 
/* good */
li + li {
  visibility: hidden;
}

继承

在能够持续的图景下,不要再度样式证明,。

CSS

/* bad */ div h1, div p { text-shadow: 0 1px 0 #fff; } /* good */
div { text-shadow: 0 1px 0 #fff; }

1
2
3
4
5
6
7
8
9
/* bad */
div h1, div p {
  text-shadow: 0 1px 0 #fff;
}
 
/* good */
div {
  text-shadow: 0 1px 0 #fff;
}

简洁

保持代码简洁。使用简写属性,制止在无需时接收三个性格。

CSS

/* bad */ div { transition: all 1s; top: 50%; margin-top: -10px;
padding-top: 5px; padding-right: 10px; padding-bottom: 20px;
padding-left: 10px; } /* good */ div { transition: 1s; top: calc(50% –
10px); padding: 5px 10px 20px; }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* bad */
div {
  transition: all 1s;
  top: 50%;
  margin-top: -10px;
  padding-top: 5px;
  padding-right: 10px;
  padding-bottom: 20px;
  padding-left: 10px;
}
 
/* good */
div {
  transition: 1s;
  top: calc(50% – 10px);
  padding: 5px 10px 20px;
}

语言

前期利用克罗地亚共和国(Republika Hrvatska卡塔尔国语并非数学公式

前面叁个参谋指南。JavaScript

/* bad */ :nth-child(2n + 1) { transform: rotate(360deg); } /* good
*/ :nth-child(odd) { transform: rotate(1turn); }

1
2
3
4
5
6
7
8
9
/* bad */
:nth-child(2n + 1) {
  transform: rotate(360deg);
}
 
/* good */
:nth-child(odd) {
  transform: rotate(1turn);
}

浏览器引擎前缀

主动删除过时的浏览器引擎前缀。假让你须要选用它们,请在行业内部属性前插入。

CSS

/* bad */ div { transform: scale(2); -webkit-transform: scale(2);
-moz-transform: scale(2); -ms-transform: scale(2); transition: 1s;
-webkit-transition: 1s; -moz-transition: 1s; -ms-transition: 1s; } /*
good */ div { -webkit-transform: scale(2); transform: scale(2);
transition: 1s; }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* bad */
div {
  transform: scale(2);
  -webkit-transform: scale(2);
  -moz-transform: scale(2);
  -ms-transform: scale(2);
  transition: 1s;
  -webkit-transition: 1s;
  -moz-transition: 1s;
  -ms-transition: 1s;
}
 
/* good */
div {
  -webkit-transform: scale(2);
  transform: scale(2);
  transition: 1s;
}

动画

前期选用过渡,并非卡通片。幸免对 opacity 和 transform
以外的个性使用动漫片。

CSS

/* bad */ div:hover { animation: move 1s forwards; } @keyframes move {
100% { margin-left: 100px; } } /* good */ div:hover { transition: 1s;
transform: translateX(100px); }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/* bad */
div:hover {
  animation: move 1s forwards;
}
@keyframes move {
  100% {
    margin-left: 100px;
  }
}
 
/* good */
div:hover {
  transition: 1s;
  transform: translateX(100px);
}

单位

在能够的情况下,使用未有单位的值。在你接纳绝对单位时优先 rem
。优用秒并非微秒。

CSS

/* bad */ div { margin: 0px; font-size: .9em; line-height: 22px;
transition: 500ms; } /* good */ div { margin: 0; font-size: .9rem;
line-height: 1.5; transition: .5s; }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/* bad */
div {
  margin: 0px;
  font-size: .9em;
  line-height: 22px;
  transition: 500ms;
}
 
/* good */
div {
  margin: 0;
  font-size: .9rem;
  line-height: 1.5;
  transition: .5s;
}

颜色

假诺您需求透明效果,请使用rgba。不然,总是利用十一进制格式。

CSS

/* bad */ div { color: hsl(103, 54%, 43%); } /* good */ div { color:
#5a3; }

1
2
3
4
5
6
7
8
9
/* bad */
div {
  color: hsl(103, 54%, 43%);
}
 
/* good */
div {
  color: #5a3;
}

绘图

当能源得以随便地因此CSS落成时,防止HTTP诉求。

CSS

/*前面叁个参谋指南。 bad */ div::before { content: url(white-circle.svg); } /* good */
div::before { content: “”; display: block; width: 20px; height: 20px;
border-radius: 50%; background: #fff; }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/* bad */
div::before {
  content: url(white-circle.svg);
}
 
/* good */
div::before {
  content: "";
  display: block;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: #fff;
}

Hacks

决不接收它们。

CSS

/* bad */ div { // position: relative; transform: translateZ(0); } /*
good */ div { /* position: relative; */ will-change: transform; }

1
2
3
4
5
6
7
8
9
10
11
/* bad */
div {
  // position: relative;
  transform: translateZ(0);
}
 
/* good */
div {
  /* position: relative; */
  will-change: transform;
}

JavaScript

性能

可读性,正确性和可表明性优先于质量。JavaScript基本上永世不会产生您的质量瓶颈。优化图像压缩、网络访谈和DOM渲染。假如你仅记得本文的一条标准,记住那条。

JavaScript

// bad (albeit way faster) const arr = [1, 2, 3, 4]; const len =
arr.length; var i = -1; var result = []; while (++i < len) { var n
= arr[i]; if (n % 2 > 0) continue; result.push(n * n); } // good
const arr = [1, 2, 3, 4]; const isEven = n => n % 2 == 0; const
square = n => n * n; const result = arr.filter(isEven).map(square);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// bad (albeit way faster)
const arr = [1, 2, 3, 4];
const len = arr.length;
var i = -1;
var result = [];
while (++i < len) {
  var n = arr[i];
  if (n % 2 > 0) continue;
  result.push(n * n);
}
 
// good
const arr = [1, 2, 3, 4];
const isEven = n => n % 2 == 0;
const square = n => n * n;
 
const result = arr.filter(isEven).map(square);

无污染

尽或许保持你的函数干净。全数函数最佳无副作用,不选取外界数据,重返新目的并不是改换现存的指标。

JavaScript

// bad const merge = (target, …sources) => Object.assign(target,
…sources); merge({ foo: “foo” }, { bar: “bar” }); // => { foo:
“foo”, bar: “bar” } // good const merge = (…sources) =>
Object.assign({}, …sources); merge({ foo: “foo” }, { bar: “bar” }); //
=> { foo: “foo”, bar: “bar” }

1
2
3
4
5
6
7
// bad
const merge = (target, …sources) => Object.assign(target, …sources);
merge({ foo: "foo" }, { bar: "bar" }); // => { foo: "foo", bar: "bar" }
 
// good
const merge = (…sources) => Object.assign({}, …sources);
merge({ foo: "foo" }, { bar: "bar" }); // => { foo: "foo", bar: "bar" }

原生

尽大概地信任原生方法。

JavaScript

前面叁个参谋指南。// bad const toArray = obj => [].slice.call(obj); // good const
toArray = (() => Array.from ? Array.from : obj =>
[].slice.call(obj) )();

1
2
3
4
5
6
7
// bad
const toArray = obj => [].slice.call(obj);
 
// good
const toArray = (() =>
  Array.from ? Array.from : obj => [].slice.call(obj)
)();

强制调换

当有要求时,拥抱隐式强制转变。不然制止它。不要盲目选拔。

JavaScript

// bad if (x === undefined || x === null) { … } // good if (x ==
undefined) { … }

1
2
3
4
5
// bad
if (x === undefined || x === null) { … }
 
// good
if (x == undefined) { … }

循环

当强反逼用可变的指标时,不要选用循环。依据 array.prototype 中的方法。

JavaScript

// bad const sum = arr => { var sum = 0; var i = -1; for
(;arr[++i];) { sum += arr[i]; } return sum; }; sum([1, 2, 3]); //
=> 6 // good const sum = arr => arr.reduce((x, y) => x + y);
sum([1, 2, 3]); // => 6

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// bad
const sum = arr => {
  var sum = 0;
  var i = -1;
  for (;arr[++i];) {
    sum += arr[i];
  }
  return sum;
};
 
sum([1, 2, 3]); // => 6
 
// good
const sum = arr =>
  arr.reduce((x, y) => x + y);
 
sum([1, 2, 3]); // => 6

假若你不可能,恐怕使用 array.prototype 方法很虐心。使用递归。

JavaScript

// bad const createDivs = howMany => { while (howMany–) {
document.body.insertAdjacentHTML(“beforeend”,
“<div></div>”); } }; createDivs(5); // bad const createDivs
= howMany => […Array(howMany)].forEach(() =>
document.body.insertAdjacentHTML(“beforeend”, “<div></div>”)
); createDivs(5); // good const createDivs = howMany => { if
(!howMany) return; document.body.insertAdjacentHTML(“beforeend”,
“<div></div>”); return createDivs(howMany – 1); };
createDivs(5);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// bad
const createDivs = howMany => {
  while (howMany–) {
    document.body.insertAdjacentHTML("beforeend", "<div></div>");
  }
};
createDivs(5);
 
// bad
const createDivs = howMany =>
  […Array(howMany)].forEach(() =>
    document.body.insertAdjacentHTML("beforeend", "<div></div>")
  );
createDivs(5);
 
// good
const createDivs = howMany => {
  if (!howMany) return;
  document.body.insertAdjacentHTML("beforeend", "<div></div>");
  return createDivs(howMany – 1);
};
createDivs(5);

Arguments

遗忘 arguments 对象。rest 参数一向是三个更加好的接纳,因为:

  1. 它是命名的,所以它给你三个函数期待arguments的越来越好的做法
  2. 它是三个真的的数组,那使得它更便于接收。

JavaScript

// bad const sortNumbers = () =>
Array.prototype.slice.call(arguments).sort(); // good const sortNumbers
= (…numbers) => numbers.sort();

1
2
3
4
5
6
// bad
const sortNumbers = () =>
  Array.prototype.slice.call(arguments).sort();
 
// good
const sortNumbers = (…numbers) => numbers.sort();

Apply

记不清 apply() 。使用 spread 操作符取代。

JavaScript

const greet = (first, last) => `Hi ${first} ${last}`; const person
= [“John”, “Doe”]; // bad greet.apply(null, person); // good
greet(…person);

1
2
3
4
5
6
7
8
const greet = (first, last) => `Hi ${first} ${last}`;
const person = ["John", "Doe"];
 
// bad
greet.apply(null, person);
 
// good
greet(…person);

Bind

当有惯用方法时,不要使用 bind() 。

JavaScript

// bad [“foo”, “bar”].forEach(func.bind(this)); // good [“foo”,
“bar”].forEach(func, this); // bad const person = { first: “John”,
last: “Doe”, greet() { const full = function() { return `${this.first}
${this.last}`; }.bind(this); return `Hello ${full()}`; } } // good
const person = { first: “John”, last: “Doe”, greet() { const full = ()
=> `${this.first} ${this.last}`; return `Hello ${full()}`; } }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// bad
["foo", "bar"].forEach(func.bind(this));
 
// good
["foo", "bar"].forEach(func, this);
// bad
const person = {
  first: "John",
  last: "Doe",
  greet() {
    const full = function() {
      return `${this.first} ${this.last}`;
    }.bind(this);
    return `Hello ${full()}`;
  }
}
 
// good
const person = {
  first: "John",
  last: "Doe",
  greet() {
    const full = () => `${this.first} ${this.last}`;
    return `Hello ${full()}`;
  }
}

高阶函数

在无需时,幸免嵌套函数。

JavaScript

// bad [1, 2, 3].map(num => String(num)); // good [1, 2,
3].map(String);

1
2
3
4
5
// bad
[1, 2, 3].map(num => String(num));
 
// good
[1, 2, 3].map(String);

组合

幸免多嵌套函数的调用。使用组合。

JavaScript

const plus1 = a => a + 1; const mult2 = a => a * 2; // bad
mult2(plus1(5)); // => 12 // good const pipeline = (…funcs) =>
val => funcs.reduce((a, b) => b(a), val); const addThenMult =
pipeline(plus1, mult2); addThenMult(5); // => 12

1
2
3
4
5
6
7
8
9
10
const plus1 = a => a + 1;
const mult2 = a => a * 2;
 
// bad
mult2(plus1(5)); // => 12
 
// good
const pipeline = (…funcs) => val => funcs.reduce((a, b) => b(a), val);
const addThenMult = pipeline(plus1, mult2);
addThenMult(5); // => 12

缓存

缓存功效测量检验、大数据结议和其余昂贵的操作。

JavaScript

// bad const contains = (arr, value) => Array.prototype.includes ?
arr.includes(value) : arr.some(el => el === value); contains([“foo”,
“bar”], “baz”); // => true // good const contains = (() =>
Array.prototype.includes ? (arr, value) => arr.includes(value) :
(arr, value) => arr.some(el => el === value) )();
contains([“foo”, “bar”], “baz”); // => true

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// bad
const contains = (arr, value) =>
  Array.prototype.includes
    ? arr.includes(value)
    : arr.some(el => el === value);
contains(["foo", "bar"], "baz"); // => true
 
// good
const contains = (() =>
  Array.prototype.includes
    ? (arr, value) => arr.includes(value)
    : (arr, value) => arr.some(el => el === value)
)();
contains(["foo", "bar"], "baz"); // => true

变量定义

优先const,再是let,然后是var。

JavaScript

// bad var obj = {}; obj[“foo” + “bar”] = “baz”; // good const obj = {
[“foo” + “bar”]: “baz” };

1
2
3
4
5
6
7
8
// bad
var obj = {};
obj["foo" + "bar"] = "baz";
 
// good
const obj = {
  ["foo" + "bar"]: "baz"
};

条件

先行使用即时推行函数表达式(IIFE和重回语句,并非 if,else if 和 switch
语句

JavaScript

// bad var grade; if (result < 50) grade = “bad”; else if (result
< 90) grade = “good”; else grade = “excellent”; // good const grade =
(() => { if (result < 50) return “bad”; if (result < 90) return
“good”; return “excellent”; })();

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// bad
var grade;
if (result < 50)
  grade = "bad";
else if (result < 90)
  grade = "good";
else
  grade = "excellent";
 
// good
const grade = (() => {
  if (result < 50)
    return "bad";
  if (result < 90)
    return "good";
  return "excellent";
})();

指标迭代

在同意的情况下防止使用 for…in

JavaScript

const shared = { foo: “foo” }; const obj = Object.create(shared, { bar:
{ value: “bar”, enumerable: true } }); // bad for (var prop in obj) { if
(obj.hasOwnProperty(prop)) console.log(prop); } // good
Object.keys(obj).forEach(prop => console.log(prop));

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const shared = { foo: "foo" };
const obj = Object.create(shared, {
  bar: {
    value: "bar",
    enumerable: true
  }
});
 
// bad
for (var prop in obj) {
  if (obj.hasOwnProperty(prop))
    console.log(prop);
}
 
// good
Object.keys(obj).forEach(prop => console.log(prop));

对象映射

当目的合法使用状态下,map
通常是二个越来越好的,更加强盛的筛选。借使有问号,请使用 map 。

JavaScript

// bad const me = { name: “Ben”, age: 30 }; var meSize =
Object.keys(me).length; meSize; // => 2 me.country = “Belgium”;
meSize++; meSize; // => 3 // good const me = new Map();
me.set(“name”, “Ben”); me.set(“age”, 30); me.size; // => 2
me.set(“country”, “Belgium”); me.size; // => 3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// bad
const me = {
  name: "Ben",
  age: 30
};
var meSize = Object.keys(me).length;
meSize; // => 2
me.country = "Belgium";
meSize++;
meSize; // => 3
 
// good
const me = new Map();
me.set("name", "Ben");
me.set("age", 30);
me.size; // => 2
me.set("country", "Belgium");
me.size; // => 3

Curry(柯里化)

柯里局可能在别的语言有它的身价,但防止在 JavaScript
使用。它经过引入外来范式,且有关的用例极不通常,使得您的代码更难阅读。

JavaScript

// bad const sum = a => b => a + b; sum(5)(3); // => 8 // good
const sum = (a, b) => a + b; sum(5, 3); // => 8

1
2
3
4
5
6
7
// bad
const sum = a => b => a + b;
sum(5)(3); // => 8
 
// good
const sum = (a, b) => a + b;
sum(5, 3); // => 8

可读性

并非通过相同聪明的本领来混淆代码的意图。

JavaScript

// bad foo || doSomething(); // good if (!foo) doSomething(); // bad
void function() { /* IIFE */ }(); // good (function() { /* IIFE */
}()); // bad const n = ~~3.14; // good const n = Math.floor(3.14);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// bad
foo || doSomething();
 
// good
if (!foo) doSomething();
// bad
void function() { /* IIFE */ }();
 
// good
(function() { /* IIFE */ }());
// bad
const n = ~~3.14;
 
// good
const n = Math.floor(3.14);

代码重用

永不惧怕成立大量小,中度可构成、可接受的函数。

JavaScript

// bad arr[arr.length – 1]; // good const first = arr => arr[0];
const last = arr => first(arr.slice(-1)); last(arr); // bad const
product = (a, b) => a * b; const triple = n => n * 3; // good
const product = (a, b) => a * b; const triple = product.bind(null,
3);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// bad
arr[arr.length – 1];
 
// good
const first = arr => arr[0];
const last = arr => first(arr.slice(-1));
last(arr);
// bad
const product = (a, b) => a * b;
const triple = n => n * 3;
 
// good
const product = (a, b) => a * b;
const triple = product.bind(null, 3);

依赖

减掉正视。第三方代码你目生。不要独自为了利用一些比较轻便复制的艺术而加载整个库:

JavaScript

// bad var _ = require(“underscore”); _.compact([“foo”, 0]));
_.unique([“foo”, “foo”]); _.union([“foo”], [“bar”], [“foo”]);
// good const compact = arr => arr.filter(el => el); const unique
= arr => […Set(arr)]; const union = (…arr) =>
unique([].concat(…arr)); compact([“foo”, 0]); unique([“foo”,
“foo”]); union([“foo”], [“bar”], [“foo”]);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// bad
var _ = require("underscore");
_.compact(["foo", 0]));
_.unique(["foo", "foo"]);
_.union(["foo"], ["bar"], ["foo"]);
 
// good
const compact = arr => arr.filter(el => el);
const unique = arr => […Set(arr)];
const union = (…arr) => unique([].concat(…arr));
 
compact(["foo", 0]);
unique(["foo", "foo"]);
union(["foo"], ["bar"], ["foo"]);

赞 6 收藏
评论

至于小编:cucr

图片 1

和讯博客园:@hop_ping
个人主页 ·
作者的稿子 ·
17

图片 2

发表评论

电子邮件地址不会被公开。 必填项已用*标注