嵌套循环以获取键和值 [英] Nested loop to get keys and values
问题描述
我有这个Javascript变量
var City = {
开罗:[
{
name: 放置1
},
{
name:< span class =code-string> 放置2
},
{
name: 放置3
}
],
Giza:[{ name: 我的位置1},{ name: 我的地方2},{ name: 我的地方3}]
}
我想循环通过它,获得关键名称(Cairo,Giza)然后循环遍历每个键以获取其数据
for (i = 0 ; i < City.Length; i ++)
{
data = 对象 .Keys(City)[i];
for (s = 0 ; s < ; data.Length; s ++)
{
value = data [s]。值跨度>;
}
}
我需要帮助。谢谢
- 更新
我可以获得密钥,但我从第二个循环中得不到任何东西来获取每个密钥值。此循环不起作用
for (s = 0 ; s < data.Length; s ++)
{
value = data [s]。 value ;
}
你的小问题是你为城市使用不同的密钥,它的名字。考虑一下:
var cities = {
开罗:[
{ name: 放置1},
{ name: 放置2},
{ name: 放置3}],
Giza:[
{ 名称: 我的地方1},
{ 名称: 我的地方2},
{ name: < span class =code-string>我的地方3}]
}
for (city < span class =code-keyword> in cities)
for ( var index = 0 ;指数<城市[城市]。长度; ++ index)
alert(city + :地名: + cities [city] ] [index] .name)
你明白了吗?
你的结构是3级,而不是2级。它不是城市,而是一组城市。每个城市都有一些你可以称之为地方的东西,也是一个集合,但表示为数组。最后,这是一个对象数组,而不是字符串,只有每个对象都有唯一的属性name。
-SA
我的解决方案:这不是您问题的具体解决方案,这是一个通用的解决方案,当您的代码没有做它应该做的事情。
您的问题是您的代码没有按照您的想法执行,您不明白为什么。
解决方案是使用调试器,它是一个了不起的工具,可以让您逐步查看代码实际执行的操作,特别注意变量。 />
对于今天的问题,您可能会发现变量data
不包含您认为的内容。
I have this Javascript variable
var City ={
"Cairo": [
{
"name": "Place 1"
},
{
"name": "Place 2"
},
{
"name": "Place 3"
}
],
"Giza":[{"name":"My Place 1"},{"name":"My Place 2"},{"name":"My Place 3"}]
}
I want to loop through it, to get the key name (Cairo, Giza) and then loop through each key to get its data
for (i=0;i < City.Length;i++)
{
data=Object.Keys(City)[i];
for (s=0;s < data.Length; s++)
{
value=data[s].value;
}
}
I need help with this. Thank you
--Update
I can get the keys but I get nothing from the second loop to get each keys value. This loop does not work
for (s=0;s < data.Length; s++)
{
value=data[s].value;
}
Your little problem is that you use different key for the city, its name. Consider this:
var cities = { "Cairo": [ { "name": "Place 1" }, { "name": "Place 2" }, { "name": "Place 3" }], "Giza":[ {"name":"My Place 1"}, {"name":"My Place 2"}, {"name":"My Place 3"}] } for (city in cities) for (var index=0; index < cities[city].length; ++index) alert(city + ": place name: " + cities[city][index].name)
Are you getting the idea?
Your structure is 3-level, not 2-level. It's not "city", it's a set of cities. Each city has something you could call "places", also a set, but expressed as an array. And finally, this is an array of objects, not string, only each object has the only property "name".
—SA
My solution: This not a specific solution to your problem, this is a general solution when your code don't do what it should.
Your problem is that your code don't do what you think it should, and you don't understand why.
The Solution is to use the debugger, its a marvellous tool that allow you to see step by step what your code is really doing, pay particularly attention to the variables.
For today's problem, you may discover that the variabledata
do not contain what you think it is.
这篇关于嵌套循环以获取键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!