开发者

How to get value from the object?

开发者 https://www.devze.com 2023-03-08 02:01 出处:网络
I wrote an object, it has 4 keys and values. How can I get the keys and values separately using a for loop?

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 开发者_StackOverflow中文版page, so a jQuery solution is ok too.


In jQuery, you can loop through with $.each.

$.each(timeObject, function(key, value) {

});

However, your loop isn't far off:

for (var x in timeObject) {
    alert('key: ' + x + ' value=' + timeObject[x]);
}

In this for..in loop, x is the key name. You can then access it on the object timeObject using the standard member operator. See the MDC documentation for for..in.


I think you sholu do something like this:

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


You almost got it. You don't need the extra value at the end.

Working code

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


If it's still actual - Object.keys() may help you. Demo: 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]]);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消