原文:https://segmentfault.com/a/1190000017171866
1. 模板字符串
1.1 模板字符串
需要拼接字符串的时候尽量改成使用模板字符串
// bad
const foo = 'this is a' + example;
// good
const foo = `this is a ${example}`;
1.2 标签模板
可以借助标签模板优化书写方式
// 例子 2-2
let url = oneLine `
www.taobao.com/example/index.html
?foo=${foo}
&bar=${bar}
`;
console.log(url); // www.taobao.com/example/index.html?foo=foo&bar=bar
2. 箭头函数
优先使用箭头函数,不过以下几种情况避免使用:
2.1. 使用箭头函数定义对象的方法
// bad
let foo = {
value: 1,
getValue: () => console.log(this.value)
}
foo.getValue(); // undefined
2.2. 定义原型方法
// bad
function Foo() {
this.value = 1
}
Foo.prototype.getValue = () => console.log(this.value)
let foo = new Foo()
foo.getValue(); // undefined
2.3. 作为事件的回调函数
// bad
const button = document.getElementById('myButton');
button.addEventListener('click', () => {
console.log(this === window); // => true
this.innerHTML = 'Clicked button';
});
3. Symbol
3.1 魔术字符串
// bad
const TYPE_AUDIO = 'AUDIO'
const TYPE_VIDEO = 'VIDEO'
const TYPE_IMAGE = 'IMAGE'
// good
const TYPE_AUDIO = Symbol()
const TYPE_VIDEO = Symbol()
const TYPE_IMAGE = Symbol()
function handleFileResource(resource) {
switch(resource.type) {
case TYPE_AUDIO:
playAudio(resource)
break
case TYPE_VIDEO:
playVideo(resource)
break
case TYPE_IMAGE:
previewImage(resource)
break
default:
throw new Error('Unknown type of resource')
}
}
3.2 私有变量
Symbol 也可以用于私有变量的实现。
const Example = (function() {
var _private = Symbol('private');
class Example {
constructor() {
this[_private] = 'private';
}
getName() {
return this[_private];
}
}
return Example;
})();
var ex = new Example();
console.log(ex.getName()); // private
console.log(ex.name); // undefined
4. Set 和 Map
4.1 数组去重
[...new Set(array)]
4.2 条件语句的优化
// 根据颜色找出对应的水果
// bad
function test(color) {
switch (color) {
case 'red':
return ['apple', 'strawberry'];
case 'yellow':
return ['banana', 'pineapple'];
case 'purple':
return ['grape', 'plum'];
default:
return [];
}
}
test('yellow'); // ['banana', 'pineapple']
// good
const fruitColor = {
red: ['apple', 'strawberry'],
yellow: ['banana', 'pineapple'],
purple: ['grape', 'plum']
};
function test(color) {
return fruitColor[color] || [];
}
// better
const fruitColor = new Map()
.set('red', ['apple', 'strawberry'])
.set('yellow', ['banana', 'pineapple'])
.set('purple', ['grape', 'plum']);
function test(color) {
return fruitColor.get(color) || [];
}
5. 函数
5.1 默认值
// bad
function test(quantity) {
const q = quantity || 1;
}
// good
function test(quantity = 1) {
...
}
// 例子 5-2
doSomething({ foo: 'Hello', bar: 'Hey!', baz: 42 });
// bad
function doSomething(config) {
const foo = config.foo !== undefined ? config.foo : 'Hi';
const bar = config.bar !== undefined ? config.bar : 'Yo!';
const baz = config.baz !== undefined ? config.baz : 13;
}
// good
function doSomething({ foo = 'Hi', bar = 'Yo!', baz = 13 }) {
...
}
// better
function doSomething({ foo = 'Hi', bar = 'Yo!', baz = 13 } = {}) {
...
}
6. 拓展运算符
6.1 arguments 转数组
// bad
function sortNumbers() {
return Array.prototype.slice.call(arguments).sort();
}
// good
const sortNumbers = (...numbers) => numbers.sort();
6.2 调用参数
// bad
Math.max.apply(null, [14, 3, 77])
// good
Math.max(...[14, 3, 77])
// 等同于
Math.max(14, 3, 77);
7. 解构赋值
7.1 对象深度解构
// bad
function test(fruit) {
if (fruit && fruit.name) {
console.log (fruit.name);
} else {
console.log('unknown');
}
}
// good
function test({name} = {}) {
console.log (name || 'unknown');
}
7.2 数组解构
// bad
const spliteLocale = locale.splite("-");
const language = spliteLocale[0];
const country = spliteLocale[1];
// good
const [language, country] = locale.splite('-');
7.3 变量重命名
let { foo, baz, name } = { foo: 'aaa', bar: 'bbb', name: 'wang' };
console.log(foo); // "aaa"
8. 增强的对象字面量
// bad
const something = 'y'
const x = {
something: something
}
// good
const something = 'y'
const x = {
something
};
9. 数组的拓展方法
9.1 keys
var arr = ["a", , "c"];
var sparseKeys = Object.keys(arr);
console.log(sparseKeys); // ['0', '2']
var denseKeys = [...arr.keys()];
console.log(denseKeys); // [0, 1, 2]
9.2 entries
var arr = ["a", "b", "c"];
var iterator = arr.entries();
for (let e of iterator) {
console.log(e);
}
9.3 values
let arr = ['w', 'y', 'k', 'o', 'p'];
let eArr = arr.values();
for (let letter of eArr) {
console.log(letter);
}
9.4 includes
// bad
function test(fruit) {
if (fruit == 'apple' || fruit == 'strawberry') {
console.log('red');
}
}
// good
function test(fruit) {
const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
if (redFruits.includes(fruit)) {
console.log('red');
}
}