js的规范写法ES5(自己以后按照这样写)
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
*/
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變量轉載于:https://www.cnblogs.com/faith3/p/6188261.html
總結
以上是生活随笔為你收集整理的js的规范写法ES5(自己以后按照这样写)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 浦发信用卡怎么查询账单分期?四种查询方法
- 下一篇: 递归下降分析