2012-03-14 74 views

回答

58

因爲"key" + test是一個表達式,而不是一個標識符,也不是一個字符串文字或數字文字,這是唯一允許作爲對象文字中的鍵的東西。

您有這樣一個動態密鑰生成的對象之後,再使用[]符號:

var test123 = {}; 
test123["key" + test] = 123; 

標識符基本上是相同的字符集,你可以調用一個變量(字母,數字,_$;可能不以數字開頭),並且字符串文字是任何以'"包圍的字符串。

所以,唯一的密鑰類型,你可以在一個對象文本使用的都是:

{ 
    a0: true, // valid identifier 
    $$_: true, // same 
    123: true, // valid numeric literal 
    012: true, // same (octal) 
    0xf: true, // same (hex) 
    "@": true, // not allowed as an identifier 
    '0a': true // same 
} 

參考:http://es5.github.com/#x11.1.5

的PropertyName

IdentifierName

串文字

NumericLiteral

+3

此外,對象字面也允許使用數字,例如'0'或'5e10'(但不是'-10',因爲'-'不是'數字字面,但一元'-'運算符)。 – 2012-03-14 19:02:01

+0

@Felix Kling:的確是他們,謝謝。 – pimvdb 2012-03-14 19:04:55

10

你可以但不能用文字符號(ES6)。

var test123 = {}; 
test123["foo" + "bar"] = 'baz'; 

test123.foobar === 'baz'; // true 
+0

感謝您的簡單回答,這就是我一直在尋找:) – 2015-02-26 03:28:44

3

您的代碼相當於test123.("key" + test) = 123這可能會更好地幫助您瞭解爲什麼它是錯誤的。

您需要["name"]表示法才能通過字符串中的名稱訪問字段。其他符號(您的和.之一)需要標識符。

-3
--HTML-- 
<div id="name1"></div> 
<div id="name2"></div> 
<div id="name3"></div> 

--JS-- 
    function getJsonData(){ 
    var hr = new XMLHttpRequest(); 
    hr.open("GET", "bookJson.json", true); 
    hr.setRequestHeader("Content-type", "application/json", true); 
    hr.onreadystatechange = function() { 
    if(hr.readyState == 4 && hr.status == 200) { 

    var data = JSON.parse(hr.responseText); 
    for(var i=0;i<3;i++){ 
    var a = "p"+(i+1)+"H"; 
    $("#name"+(i+1)).html(data[objName][a]); 
    } 


    } 

} 
    hr.send(null); 
} 

---JSON--- save JSON file name as bookJson.json 
{ "objName": 
    { 
    "p1H":"content1", 
    "p2H":"content2", 
    "p3H":"content3", 
    } 
    } 
----------------------------------- 
json object key name p1H,p2H,p3H ... 
We want to dynamically get this keys in javacript instead of **data[objName].p1H**. you can get dynamical key like **data[objName]["p1H"]** 
+0

請提供解釋您的答案,以幫助其他用戶的網站。僅有代碼的答案不是很有用,往往被標記爲低質量並可能被刪除。 – Tristan 2016-02-05 02:18:58

+0

感謝您的建議,我提供了我的答案的解釋... – 2016-02-10 04:44:01

1

JavaScript提供兩種方法來定義一個對象的屬性:

  1. object.propertyName =值;

在這種情況下,propertyName是不可編輯的,並且是不可計算的。你不能執行以下操作:

object.('property'+'Name') 

,你可以看到

object = {propertyName:value}; 
    object = {'propertyName':value}; 

它們相等

  • 你可以使用一個變量作爲屬性名稱與「[]」;
  • ,你可以這樣做:

    var a = "propertyName"; 
    object[a] = value; 
    

    ,這個時候你必須使用一個字符串

    object[propertyName] = value;//error 
    object["propertyName"] = value;//correct 
    object = {'propertyName':value};//correct 
    object = {propertyName:value};//correct 
    
    29

    隨着ES6,您可以將對象文本中定義的動態密鑰:

    const test = "test123" 
    const test123 = { ["key" + test]: 123 };