2012-03-02 82 views

回答

4

那些被稱爲Member Operators,並沒有在該鏈路上他們信息的好一點。

唯一真正的區別是,括號符號讓你不服從變量的命名規則,做這樣的事情:

o["3213adascas  #@%!"] = 5; 

儘管下面顯然是一個語法錯誤:

o.3213adascas  #@%! = 5; 

此外,由於括號表示法需要一個字符串,您可以使用它的變量:

var o = { x:1, y:2 }; 
var member = 'y'; 
console.log(o[member]); // Outputs 2 
2

o.x實際上只是o["x"]的語法糖。他們做同樣的事情。但是,方括號表示法允許您例如使用可變作爲屬性名的值來訪問:

var someString = "x"; 
o[someString]; 

除了這一點,如果屬性名稱是不是一個有效標識符,方括號必須使用:

var myObj = { 
    "space property": 1 
}; 
myObj["space property"]; 
2

沒有區別 - 同樣的事情......但並實現與空間/晦澀字符鍵:

o['something here'] = "test"; 

將例如工作,但是這不會:

o.something here = "test"; 
2

的方括號有一個優點。您可以動態設置屬性。

From JavaScript Garden

var foo = {name: 'Kitten'} 
foo.name; // kitten 
foo['name']; // kitten 

var get = 'name'; 
foo[get]; // kitten 

foo.1234; // SyntaxError 
foo['1234']; // works 

Both notations are identical in their workings, with the only difference being that the square bracket notation allows for dynamic setting of properties, as well as the use of property names that would otherwise lead to a syntax error.

2

這兩個完全一樣的東西。然而,括號表示法(o["x"]),可以做兩件事情,你不能用點號(o.x)做:

  1. 訪問屬性與任意字符串。例如,o["function"]o["432 %^$ ==="]是有效的語法,但o.function無效,因爲function是關鍵字,並且o.432 %^$ ===無效,因爲它構成語法錯誤。

  2. 設置對象的動態屬性。您可以使用括號表示法做var str = "prop";並訪問o[str]