1. 程式人生 > 實用技巧 >web前端js中ES6的規範寫法

web前端js中ES6的規範寫法

1、引號的使用,單引號' ' 優先(如果不是引號巢狀,不要使用雙引號)

正常情況:console.log('hello there') ,雙引號轉碼:$("<divclass='box'>")

2、空格的使用問題:(關鍵字後 符號後 排版函式賦值符號= )等

a函式的括號:function hello(name){} 看 (引數)的"括號外左右"( ) 是有空格的,"括號內name左右" 是沒有空格的 b 關鍵字後需要空格:if(condition) { ... } if和()之間需要有空格 c 賦值符號 = 兩邊需要有空格 :varx=2 賦值符號 = 兩邊需要空格 d 字串拼接符號 + 兩邊需要空格:varmessage = 'hello, '+name+'!' 常量和變數之間的+號,左右兩邊需要空格 e 逗號,前面不要留空格,後面留空格:varlist = [1,2,3,4] function greet (name,options) { ... } 逗號前面不留後面留空格

3、同行不同行的問題:

if () {}else{}中:  } else { 要在一行內
if (true) {
  // 
}  else   {
  //
}

  

4、不寫沒有使用過的變數,如果定義了一個變數,後來一直沒有參與過運算,那麼不應該定義這個變數。

5、用=== 代替 ==,比較相等的時候,因為 == 會多一步資料轉換,但是當在 if (a!=undefiend) {}條件中, a!=undefiend同時有a!==undefiend和a!==null的雙重意思(null == undefined)

6、習慣給window的屬性和方法加上window,例外的幾個不用加window:document ,console ,navigator。 如:window.alert('hi')

7、同一個連寫方法很長要換行縮排問題,js中三元運算子,jq中的連綴等

varlocation = env.development ? 'localhost' : 'www.api.com' 一行內寫法 連綴寫法:
var leds = stage.selectAll('.led')
    .data(data)
  .enter().append('svg:svg')
    .class('led', true)
    .attr('width', (radius + margin) * 2)
  .append('svg:g')
    .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')')
    .call(tron.led);

  

8、註釋問題:要有與前一行要空一行,另外不要無緣無故有大片的空白行// 後面空一格

var value  =  'hello world';空一行

//這裡是註釋   
console.log(value)

  

多行註釋:(這也可以用到版權資訊註釋

/**
* make() returns a new element
* based on the passed in tag name
*
* @param <String> tag
* @return <Element> element
*/

  

9、開頭問題:不要 ( [ ` 開頭, 在開頭前要加上;號

;(function () {window.alert('ok')}())
;[1, 2, 3].forEach(bar)    
;`hello`.indexOf('o')

  

10、物件和陣列的建立問題:varitem = {}; 不用new Object()方式 陣列:vararr = []

11、超過80個字的字串連線問題:

var errorMessage = 'This is a super long error that ' +
   'was thrown because of Batman.'+
     'When you stop to think about ' +
    'how Batman had anything to do '+
     'with this, you would get nowhere ' +
   'fast.';

  

迴圈 或者 多行字串 用join方法來構建
function inbox(messages) {
  items = []; 
  for(i = 0; i < length; i++) {
       items[i] = messages[i].message;
  } 
  return'<ul><li>'+ items.join() + ;
}

  

12、對數字使用 parseInt 並且總是帶上型別轉換的基數. varval = parseInt(inputValue,10);

13,布林值轉換 用Boolean() 或者 !! var hasAge = Boolean(age); var hasAge = !!age;

14、命名問題:

a 命名私有屬性時前面加個下劃線 _ 如:建構函式中 this._firstName = 'Panda'; var _firstName = firstName; b jq變數命名加上個$,用來區分js變數