ES6提出了兩個新的聲明變量的命令:let 和 const 1. 建議不再使用var,而使用let 和const 。優先使用const。
//badvar a = 1, b =2 , c = 3;// goodconst [a,b,c] = [1,2,3];2.靜態字符串一律使用單引號或反引號,不建議使用雙引號。動態字符使用反引號。
//bad const a = "foobar"; const b = 'foo'+a+'bb';// good const a = 'foobar';const b = `foo${a}bar`;3.優先使用解構賦值
const arr = [1, 2, 3, 4];// badconst first = arr[0];const second = arr[1];// goodconst [first, second] = arr;函數的參數如果是對象的成員,優先使用解構賦值。
// badfunction getFullName(user) { const firstName = user.firstName; const lastName = user.lastName;}// goodfunction getFullName(obj) { const { firstName, lastName } = obj;}// bestfunction getFullName({ firstName, lastName }) {}如果函數返回多個值,優先使用對象的解構賦值,而不是數組的解構賦值。這樣便于以后添加返回值,以及更改返回值的順序。
// badfunction PRocessInput(input) { return [left, right, top, bottom];}// goodfunction processInput(input) { return { left, right, top, bottom };}const { left, right } = processInput(input);5.對象的屬性和方法盡量采用簡潔表達法,這樣易于描述和書寫
// bad var ref = 'some value';const atom = { ref:ref, value:1, addValue:function(value){ return atom.value + value; },}// good const atom = { ref, value:1, addValue(value){ return atom.value + value; }}使用擴展運算符(…) 復制數組,使用Array.from 方法將類似數組的對象轉為數組。
不在使用arguments (偽數組) 而是用…rest 運算符(真數組)。
學習鏈接: Airbnb前端規范
阿里員工前端規范
es6參考標準
新聞熱點
疑難解答