Airbnb Javascript Style Guide - huyx/1 GitHub Wiki

链接:

尽量用 const, let, 避免使用 var

const foo = 1;
const foo = [1, 2];
const bar = foo;
let bar = foo;

避免用关键字作为 key.

用 Array#push 附加元素到数组:

const items = [];
const items[items.length] = 'BAD';
const items.push('GOOD');

拷贝数组:

Array#from

类和构造器

// 定义类的方法
class Queue {
    constructor() {
	}
	toString() {
	}
}

// 继承
class PeekableQueue extends Queue {
	constructor(...args) {
		super(...args);
	}
}

// return this 方便链式操作

Iteraotrs 和 Generators

const numbers = [1, 2, 3, 4, 5];

let sum = 0;
numbers.forEach(num => sum += num);
const sum = numbers.reduce((total, num) => total + num, 0);

逗号:

const items = [
	1,
	1,
	2,      // 结尾总是加上 , 会省很多事,JSON 不可以, JavaScript 是可以的
];

类型转换:

const s = String(i);
const i = Number(s);
const i = parseInt(s, 10);

其他

[1, 2, 3].map(x => x + 1);
const [ x, y ] = point;                 // Array Destructuring
const { name, age } = user;             // Object Destructuring
function func({ name, age }) {}         // Object Destructuring
const name = 'Tom';                     // 注意不要用 "Tom"
const message = `How are you, ${name}`; // OK

// 立即调用的函数表达式 (IIFE)
(() => {
  console.log('Welcome to the Internet. Please follow me.');
})();

// 拷贝数组
const itemsCopy = [...items];

// ... 语法
function concatenateAll(...args) {
	return args.join('');
}

const key = Object.prototype.hasOwnProperty.call(obj, 'key') ? obj.key : 1;

// 使用函数表达式时,使用箭头函数符号
[1, 2, 3].map((x) => { x * x; });

const item = {};  // 不要用 new Object()
const items = []; // 不要用 new Array()