我写了一个对象,它有 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 解决方案也可以。
最佳答案
在 jQuery 中,您可以使用 $.each
进行循环.
$.each(timeObject, function(key, value) {
});
但是,您的循环离我们不远了:
for (var x in timeObject) {
alert('key: ' + x + ' value=' + timeObject[x]);
}
在这个for..in
循环中,x
是键名。然后,您可以使用标准成员运算符在对象 timeObject
上访问它。参见 the MDC documentation for for..in
.
关于javascript - 如何从对象中获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6123244/