问题
I'm attempting to pass a function an array that should run through a loop and call a db.transaction for each incremented SQL statement.
function updateColorData (colorArray) {
for (var i=0; i<colorArray.length; i++) {
var sql = 'INSERT INTO SPColorData (color) VALUES (\''+colorArray[i]+'\')';
if (i < colorArray.length-1) {
db.transaction(function (tx) {tx.executeSql(sql, [], gameOptionSuccess, errorCB)}, errorCB);
} else {
db.transaction(function (tx) {tx.executeSql(sql, [], colorDataQuery, errorCB)}, errorCB);
}
}
}
As a test I'm calling the updateColorData function passing in an array like this
['one', 'two', 'three', 'four']
but when I have the database read back the information it received I'm getting
['four', 'four', 'four', 'four']
I realize that calling 4 database transactions in a loop like this is not the most efficient method but I'm not sure why this isn't working or what other method to try.
Thanks!
回答1:
You need to create a new scope for i
before you call the database function; try this:
function updateColorData (colorArray) {
for (var i=0; i<colorArray.length; i++) {
(function(i){
var sql = 'INSERT INTO SPColorData (color) VALUES (\''+colorArray[i]+'\')';
if (i < colorArray.length-1) {
db.transaction(function (tx) {tx.executeSql(sql, [], gameOptionSuccess, errorCB)}, errorCB);
} else {
db.transaction(function (tx) {tx.executeSql(sql, [], colorDataQuery, errorCB)}, errorCB);
}
})(i);
}
}
That creates an individual function scope for each value of i
, using an anonymous function. You need to do this because the for
loop in your original example keeps updating i
without waiting for your database function to return. So you need to create "safe" contexts for your database functions to run without the for
loop changing the value of i
, and that's exactly what the anonymous functions provide.
来源:https://stackoverflow.com/questions/28002040/javascript-sql-insert-loop