JavaScript中用字面量建立對象介紹_javascript技巧

來源:互聯網
上載者:User

JavaScript中可以用字面量來直接建立一個新對象:


複製代碼 代碼如下:

var obj = {a:27, "b":99};


如上所述,在用字面量來建立對象的時候,對象中的property定義可以用單引號或雙引號來包括,也可以忽略引號。不過,當property中出現空格、斜杠等特殊字元,或者使用的property與JS關鍵詞衝突時,則必須使用引號。

在用字面量來建立對象的時候,property可以是Null 字元串,property中也可以出現空格:


複製代碼 代碼如下:

//empty string is allowed as object property
var o = {"":88, "p":99};
console.log(o);//Object { =88, p=99}

//spaces can be included in property
var o2 = {"good score":99, "bad score":52};
console.log(o2);//Object {good score=99, bad score=52}


值得注意的是,即使使用的字面量相同,每次使用字面量時,JavaScript都會建立一個全新的對象:


複製代碼 代碼如下:

//every object literal creates a new and distinct object.
var x = {a:18, b:28};
var y = {a:18, b:28};
console.log(x === y);//false


在字面量中,如果最後多出一個逗號(“}”字元前出現”,”),那麼有一些JavaScript解譯器將報錯。事實上,在IE7中,這種行為將導致瀏覽器假死等問題。在ECMAScript 5標準中,”}”字元前出現”,”是合法的,該逗號會被直接忽略掉。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.