这是我的对象:
Customer{"id": "0001", "name": "ivan" , "country" {"city" : "Peru"}}
So:括号的正确使用形式是什么?上下文在jquery中each:
$。每个(datos, function (index, data) {}
1° data["country"["city"]] >> the result should be "Peru"
2° data["country"]["city"] >> the result should be "Peru"
或者什么是正确的形式?
我相信你的意思是你的对象是:
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);
. .是的,我可以自由地添加实际的国家,而不仅仅是城市,但我想这篇文章证明了这一点,你可以用点符号customer.country.finland
或撇号customer['country']['finland']
检索值。但是,如果像这样使用数字作为JavaScript对象键:
var customer = {
1: "Mauno"
};
您只能使用撇号检索它:customer['1']
试图像customer.1
一样使用它将导致JavaScript错误。