javascript: Javascript 風格嚮導

來源:互聯網
上載者:User

序
  大部分針對Javascript最合理的方法歸納。
類型
? 原始類型:我們可以直接使用值。
  ο  string
  ο  number
  ο  boolean
  ο  null
  ο  undefined
SearchIndex
var foo = 1,
bar = foo;
bar = 9;
console.log(foo, bar); // => 1, 9
SearchIndex
?   複合類型:我們通過`引用`對值進行間接訪問。
  ο  object
  ο  array
  ο  function
SearchIndex
var foo = [1, 2],
bar = foo;
bar[0] = 9;
console.log(foo[0], bar[0]); // => 9, 9
SearchIndex
 
Objects
? 使用{}建立對象。
// bad
var item = new Object();
// good
var item = {};
? 不要使用保留字作為關鍵字。
SearchIndex
// bad
var superman = {
class: 'superhero',
default: { clark: 'kent' },
private: true
};
// good
var superman = {
klass: 'superhero',
defaults: { clark: 'kent' },
hidden: true
};
SearchIndex
Arrays
? 使用[]建立數組
// bad
var items = new Array();
// good
var items = [];
? 如果你不知道數組長度,使用Array#push。
SearchIndex
var someStack = [];
// bad
someStack[someStack.length] = 'abracadabra';
// good
someStack.push('abracadabra');
SearchIndex
  ? 當你需要複製數組的時候,請使用Array#slice。
SearchIndex
var len = items.length,
itemsCopy = [],
i;
// bad
for (i = 0; i < len; i++) {
itemsCopy[i] = items[i];
}
// good
itemsCopy = items.slice();
SearchIndex
Strings
? 對於字串,我們使用單引號''。
SearchIndex
// bad
var name = "Bob Parr";
// good
var name = 'Bob Parr';
// bad
var fullName = "Bob " + this.lastName;
// good
var fullName = 'Bob ' + this.lastName;
SearchIndex
? 超過80個字元的字串,我們使用串聯符號(\),讓字串多行顯示。
? 注意:如果過度使用帶串聯符號的字元可能會影響到效能。
 
SearchIndex
// bad
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.';
// bad
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.';
// good
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.';
SearchIndex
  
? 當我們在編程的時候,需要拼接出一個字串,我們可以使用Array#join 代替字串串連。尤其是對IE瀏覽器。
SearchIndex
var items,
messages,
length, i;
messages = [{
state: 'success', 本文連結http://www.cxybl.com/html/wyzz/JavaScript_Ajax/20130709/39005.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.