標籤:top sla color 習慣 returns ... 引號 bsp ons
1、引號的使用,單引號‘ ‘ 優先(如果不是引號嵌套,不要使用雙引號)
正常情況:console.log(‘hello there‘) 雙引號轉碼: $("<div class=‘box‘>")
2、空格的使用問題:(關鍵字後 符號後 排版 函數 賦值符號= )等 a 函數的括弧:function hello (name) {} 看 (參數)的 "括弧外左右"( ) 是有空格的,"括弧內name左右" 是沒有空格的 b 關鍵字後需要空格:if (condition) { ... } if和()之間需要有空格 c 賦值符號 = 兩邊需要有空格 :var x = 2 賦值符號 = 兩邊需要空格 d 字串拼接符號 + 兩邊需要空格:var message = ‘hello, ‘ + name + ‘!‘ 常量和變數之間的+號,左右兩邊需要空格 e 逗號,前面不要留空格,後面留空格:var list = [1, 2, 3, 4] function greet (name, options) { ... } 逗號前面不留後面留空格 3、同行不同行的問題: if () {} else {}中: } else { 要在一行內 if (XXX) { // } 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中的連綴等 var location = env.development ? ‘localhost‘ : ‘www.api.com‘ 一行內寫法 var location = 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、對象和數組的建立問題:var item = {}; 不用new Object()方式 數組:var arr = [] 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 並且總是帶上類型轉換的基數. var val = parseInt(inputValue, 10); 13,布爾值轉換 用Boolean() 或者 !! var hasAge = Boolean(age); var hasAge = !!age; 14、命名問題: a 命名私人屬性時前面加個底線 _ 如:建構函式中 this._firstName = ‘Panda‘; var _firstName = firstName; b jq變數命名加上個$,用來區分js變數
js的規範寫法ES5(自己以後按照這樣寫)