简体   繁体   中英

How to Loop through JavaScript object?

I have simple JS loop

jQuery('#checkbox-counter').live('click', function(){
    jQuery.get('index.php?option=get_site_list=true', 
        function(data){
            console.log(data[1]);
            for(var index in data[1].id){
                console.log(data[1].id[index]);
                console.log(data[1].name[index]);
            }
        },
        'JSON'
    )
});

The problem is shown in the screen

在此处输入图片说明

It also prints some jquery code(in source) or shows functions in console... Where is the problem?

The data[1].id and data[1].name properties you are looping through are arrays, so you should use a conventional for loop rather than for..in :

        for(var index = 0; index < data[1].id.length; index++){
            console.log(data[1].id[index]);
            console.log(data[1].name[index]);
        }

When you use for..in it gives you other properties besides just the numerically indexed ones.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM