循环仅执行for循环的最后一个元素

时间:2017-07-13 01:59:03

标签: javascript arrays loops for-loop

当变量form_loop(带有for循环)执行时,它只执行其数组的最后一个元素('f14'一个),我试过console.log查询并输出如下: 对于第一个查询(这是正确的), "SELECT * FROM f11 where eacode='4'" "SELECT * FROM f12 where eacode='4'" "SELECT * FROM f13 where eacode='4'" "SELECT * FROM f14 where eacode='4'"

对于第二个查询(这是错误的),
"INSERT IGNORE INTO f14 (...) VALUES(...);" "INSERT IGNORE INTO f14 (...) VALUES(...);" "INSERT IGNORE INTO f14 (...) VALUES(...);" "INSERT IGNORE INTO f14 (...) VALUES(...);"

在那里,它只执行数组的最后一个元素,我希望在第二个查询中输出如下... "INSERT IGNORE INTO f11 (...) VALUES(...);" "INSERT IGNORE INTO f12 (...) VALUES(...);" "INSERT IGNORE INTO f13 (...) VALUES(...);" "INSERT IGNORE INTO f14 (...) VALUES(...);"

var col = [];
var values = [];
var sql = "";
var rn = 0;
var forms = ['f11', 'f12', 'f13', 'f14'];
var form_loop;

for (var f in forms) {
  form_loop = forms[f];
  db2.all("SELECT * FROM " + form_loop + " where eacode='" + eacode + "'", function(err, rows) {

      for (var i = 0; i < rows.length; i++) {
        for (var k in rows[i]) {
          col.push(k);
          values.push(rows[i][k]);
        }
      }
      sql = "INSERT IGNORE INTO " + form_loop + " (" + col.join(",") + ") VALUES('" + values.join("','") + "');";
      connection.query(sql, function(err, rows) {
        if (err) console.log("Error number : " + err);
        rn++;
      });
      col = [];
      values = [];
    }
  });
}

0 个答案:

没有答案