標籤:foo nbsp get roc first sel 中文 internet end
中文原地址
1.對所有的引用使用 const 而非 var。這能確保你無法對引用重複賦值。
當需要變動引用時,使用let。
const和let都是塊級範圍。
2.建立對象的方式:
const item = {};
使用對象屬性的簡寫,且為簡寫的屬性分組。
3.建立數組的方式:
const arr = [ ];
使用arr.push()去替代直接賦值。
使用拓展運算子去賦值數組: arrCopy = [...arr];
使用Array.from()把一個類數組對象轉換成數組:
const foo = document.querySelectorAll(‘.foo‘);
const nodes = Aarry.from(foo);
4.解構:
使用解構存取和使用多屬性對象:
function getFullName({ firstName, lastName }) { return `${firstName} ${lastName}`;}
對數組也使用解構賦值:
const arr = [1, 2, 3, 4];const [first, second] = arr; // 等同於first = arr[0],second = arr[1]
返回多個值時使用對象解構:這樣不用在意屬性的順序
function returnInput (input) { ... return { left, right, top, bottom }; }const { left, right } = processInput(input);
5.Strings
程式化產生字串時,使用模板字串代替字串連結
function sayHi(name) { return `How are you, ${name}?`;}
6.函數
使用函式宣告代替函數運算式
function foo() {}
立即調用的函數運算式:
(()=> { console.log(‘Welcome to the Internet. Please follow me.‘);})();
永遠不要在非函數代碼塊(if,while)中聲明一個函數,把那個函數賦給一個變數。
let test;if (current) { test = () => { ... };}
不要使用arguments,可以選擇rest文法...替代。rest是一個真正的數組,且能明確你要傳入的參數
function cont(...args) { return args.join(‘‘);}
直接給函數的參數指定預設值,不要使用一個變化的函數參數
function fn(opts = {}) {...}
7.構造器
總是使用class,避免直接操作prototype。
使用extends繼承。
方法可以返回this來協助鏈式調用。
未完
Airbnb Javascript 代碼規範重要點總結es6