简体   繁体   English

javascript for循环仅返回最后一个元素

[英]javascript for loop only return the last element

Why the loop only return the last value? 为什么循环只返回最后一个值?

Can someone help me to get all the values return in the SQL insert 有人可以帮助我获取SQL insert返回的所有值

tableau.forEach(function(obj) {

    for(let i = 0; i < obj.produits.length; i++) {
        let bd_nom = obj.produits[ii].nom
        let bd_description = obj.produits[ii].description
        let bd_titre = obj.titre

        records = [[bd_nom, bd_description, bd_titre]]

        con.connect(function(err) {
            let sql = "INSERT INTO scrapeded (nom, text, titre) VALUES ?";
            con.query(sql, [records], function (err, result) {
                console.log(result)
                console.log("Nombre de rangée affectée : " + result.affectedRows)
                console.log("Nombre d'enregistrement affectée avec avertissement : " + result.warningCount)
                console.log("Message du serveur mySQL : " + result.message)
            })
         })
      }
  })

You're implicitly assigning and reassigning to the global variable records on each iteration. 您将在每次迭代时隐式分配和重新分配给全局变量records So, by the time the asynchronous query starts, the main thread has ended and records remains as the last value it was assigned. 因此,到异步查询开始时,主线程已经结束,并且records保留为其分配的最后一个值。

Declare it with const instead to ensure that there's a new binding for each iteration. const声明它,以确保每次迭代都有一个新的绑定。

Also, there's no need to declare an array and then immediately destructure it to select the first element - instead, simply declare records as a single-dimensional array with two items: 同样,也无需声明数组,然后立即对其进行分解以选择第一个元素-只需将records声明为具有两个项目的一维数组即可:

tableau.forEach(function(obj) {
  for(let i = 0; i < obj.produits.length; i++) {
    let bd_nom = obj.produits[ii].nom
    let bd_description = obj.produits[ii].description
    let bd_titre = obj.titre

    const records = [bd_nom, bd_description, bd_titre]

    con.connect(function(err) {
      let sql = "INSERT INTO scrapeded (nom, text, titre) VALUES ?";
      con.query(sql, records, function (err, result) {
        console.log(result)
        console.log("Nombre de rangée affectée : " + result.affectedRows)
        console.log("Nombre d'enregistrement affectée avec avertissement : " + result.warningCount)
        console.log("Message du serveur mySQL : " + result.message)
      })
    })
  }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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