括号表示法+ javascript

这是我的目标:

Customer{"id": "0001", "name": "ivan" , "country" {"city" : "Peru"}} 

那么:使用brakets的正确forms是什么? 每个上下文都在jquery中:

$。 每个(数据,function(索引,数据){}

 1° data["country"["city"]] >> the result should be "Peru" 2° data["country"]["city"] >> the result should be "Peru" 

或者什么是正确的forms?

我相信你说你的目标是:

 Customer = { id: "0001", name: "ivan", country: { city : "Peru" } } 

在这种情况下,您的语法将是

 Customer.country.city 

要么

 Customer["country"]["city"] 

或者这两者的任何组合

另请注意, Customer[country[something]]也可以是有效的语法,但似乎不是您的情况

 Customer = { id: "0001", name: "ivan", country: { city : "Peru" } } country = { key: 'country' } Customer[country['key']]['city'] 

也会回到你的Peru城市

这不是JavaScript对象:

 Customer[id: "0001"; name: "ivan" ; country [city : "Peru"]] 

这是JavaScript对象中的一个对象:

 var customer = { id: "0001", name: "ivan", country: { finland: { city: "Helsinki" } } }; 

你会用它:

 console.log(customer.country.finland.city); 

或这个:

 console.log(customer['country']['finland']['city']); 

或混合….

 console.log(customer['country'].finland.city); 

..并且是采取自由添加实际国家,而不仅仅是城市,但我想这篇文章certificate了这一点,你可以用点符号customer.country.finland或撇号customer['country']['finland']检索值..但是,如果您使用数字作为JavaScript对象键,如下所示:

 var customer = { 1: "Mauno" }; 

您只能使用撇号检索它: customer['1']尝试像customer.1一样使用它将导致JavaScript错误。