简体   繁体   中英

How do you loop through the field name in javascript recordset?

I'm using the following code to query a sqlite database using javascript and everything is working fine:

function getQueryRecord(tx, rs) {
                var stringResult = '';
                for(i=0;i<rs.rows.length;i++)
                {
                    r =rs.rows.item(0);
                                    $('#someting').append(r['field1'] + ' ' + r['field2']);
                }
            }

            function getUserGroup()
            {

                var db = window.openDatabase("scores", "", "Previous Scores", 1024*1000);

                db.transaction(function(tx) {
                    tx.executeSql('SELECT * FROM user_group', [], getQueryRecord);
                 });
            }

Is it possible to do something like the following in getQueryRecord to loop through all the field? If yes, what is the correct syntax?

for(k=0;k<r.fields.length;i++)
{
  $('#something').append(r[k]);
}

Thank you.

Have you tried the for...in syntax:

for(k in r) {
   if (r.hasOwnProperty(k))
      $('#something').append(r[k]);
}

Within the loop k will be equal to the name of the first property, then the second property, etc. (Though having said "first" and "second" the order of iteration is arbitrary.)

The if statement with .hasOwnProperty() is "optional" depending on your object structure/heirarchy: it tests whether a particular property is a "direct" property of the object or a property from somewhere up the prototype chain (noting that the for...in structure returns both types of properties). If you're not sure if you need it then you probably do.

Note: this technique applies to JavaScript objects in general, not specifically to your database objects.

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