如何从对象中获取价值?
我写了一个对象,它有 4 个键和值。如何使用 for
循环分别获取键和值?
我尝试了下面的代码,但没有运气。
var timeObject = {
getNewYorkLocalTime: 'getTime.php?lat=40.7143528&lan=-74.0059731',
getLondonLocalTime: 'getTime.php?lat=51.5001524&lan=-0.1262362',
getChennaiLocalTime: 'getTime.php?lat=13.060422&lan=80.249583',
getBangaloreLocalTime: 'getTime.php?lat=12.9715987&lan=77.5945627'
}
for (var x in timeObject) {
alert(timeObject[x].value);
}
谁能帮助我吗?我在此页面中使用 jQuery,因此 jQuery 解决方案也可以。
I wrote an object, it has 4 keys and values. How can I get the keys and values separately using a for
loop?
I tried the below code, but no luck.
var timeObject = {
getNewYorkLocalTime: 'getTime.php?lat=40.7143528&lan=-74.0059731',
getLondonLocalTime: 'getTime.php?lat=51.5001524&lan=-0.1262362',
getChennaiLocalTime: 'getTime.php?lat=13.060422&lan=80.249583',
getBangaloreLocalTime: 'getTime.php?lat=12.9715987&lan=77.5945627'
}
for (var x in timeObject) {
alert(timeObject[x].value);
}
Can anyone help me? I'm using jQuery in this page, so a jQuery solution is ok too.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 jQuery 中,您可以使用
$.each
进行循环。但是,您的循环并不遥远:
在此
for..in
循环中,x
是键名称。然后,您可以使用标准成员运算符在对象timeObject
上访问它。请参阅for..in 的 MDC 文档
。In jQuery, you can loop through with
$.each
.However, your loop isn't far off:
In this
for..in
loop,x
is the key name. You can then access it on the objecttimeObject
using the standard member operator. See the MDC documentation forfor..in
.我认为你应该做这样的事情:
I think you sholu do something like this:
你几乎明白了。最后不需要额外的
值
。工作代码
You almost got it. You don't need the extra
value
at the end.Working code
如果它仍然是实际的 - Object.keys()< /a> 可能会帮助你。演示:http://jsfiddle.net/SK4Eu/
If it's still actual - Object.keys() may help you. Demo: http://jsfiddle.net/SK4Eu/