如何从对象中获取价值?

时间:2011-05-25 10:47:59

标签: javascript jquery json

我写了一个对象,它有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解决方案也可以。

4 个答案:

答案 0 :(得分:2)

在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

答案 1 :(得分:1)

我认为你应该这样做:

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) {
    //use this check to avoid messing up with prototype properties
    if (timeObject.hasOwnProperty(x)) {
        alert(timeObject[x]);
    }
}

答案 2 :(得分:0)

你几乎得到了它。您最后不需要额外的value

工作代码

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) {
    console.log(timeObject[x]);
}

答案 3 :(得分:0)

如果它仍然存在 - Object.keys()可能对您有所帮助。演示:http://jsfiddle.net/SK4Eu/

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'
}

var keys = Object.keys(timeObject),
    keysLength = keys.length;

for (var i = 0; i < keysLength; i++) {
    alert(timeObject[keys[i]]);
}