bracket notation + javascript

落花浮王杯 提交于 2019-12-11 09:05:30

问题


This is my object :

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

So: Whats the correct form to use brakets? the context is in a jquery each:

$. each (datos, function (index, data) { }

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

or whats is the form correct?


回答1:


I belive you are saying that your object is :

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

In this case your syntax would be either

Customer.country.city

or

Customer["country"]["city"]

or any mix of this two

Note also that Customer[country[something]] can also be valid syntax, but doesnt seem to be in your case

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


country = {
   key: 'country'
}

Customer[country['key']]['city'] 

would also return you city Peru




回答2:


This is not an JavaScript object:

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

This is an object in JavaScript object:

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

You would use it with this:

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

or this:

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

or with mixing....

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

..and yes took a freedom of adding actual country, not just city but I guess this post demonstrates the point, you can either retrieve values with dot notation customer.country.finland or apostrophes customer['country']['finland'] .. However, if you are using numbers as JavaScript object key like this:

var customer = {
  1: "Mauno"
};

You can retrieve it only using apostrophes as: customer['1'] trying to use it like customer.1 will result in a JavaScript error.



来源:https://stackoverflow.com/questions/22720296/bracket-notation-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!