2011-05-25 230 views
4

我寫了一個對象,它有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解決方案也可以。

回答

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]); 
} 
1

我想你sholu做這樣的事情:通過與$.each

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]); 
    } 
} 
+0

據我所知,原型屬性不會因爲你有對象,而不是本地陣列工作適用在這裏。 – JohnP 2011-05-25 10:56:14

+0

@JohnP除非你定義了'Object.prototype.contains'或者其他。 – lonesomeday 2011-05-25 11:04:36

+0

@JohnP如果你不需要它,如果你濾除了任何原型鏈,我認爲我總是更好。 – 2011-05-25 11:14:10

2

在jQuery中,你可以循環。

$.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

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]]); 
}