索引循环不改变

我试图从twitter,在控制台上收集鸣叫,如果我select5个鸣叫来收集它显示每一个,但如果我selectMySQL模块插入到数据库它插入最后一行5次。

无法弄清楚如何解决它。

再问一次,在过去的三个小时内没有运气使这个脚本工作。 指出for循环不改变索引里面的函数 。 有人可以帮我解决这个问题吗?

for (var i = 0; i < data.length ; i++) { // get all the messages from username, devfined in search term var retweetId_str = data[i].id_str; // id_str = id not rounded more precise console.log('id_str:', retweetId_str); // //id_str: 656087507604402176 //id_str: 656063345192255488 //id_str: 656063056947126272 //id_str: 656062911530606592 //id_str: 656062750574182400 con.query('SELECT retweetid_str FROM droid_retweets WHERE retweetId_str=?', retweetId_str, function(error,result){ console.log('id_str:', retweetId_str); //id_str: 656062750574182400 //id_str: 656062750574182400 //id_str: 656062750574182400 //id_str: 656062750574182400 //id_str: 656062750574182400 }); } // for close 

这是因为JavaScript中的closures。

这个答案应该有助于解释它,并且有一些方法来处理它。

最简单的就是使用.forEach()

 data.forEach(function(d) { // get all the messages from username, devfined in search term var retweetId_str = d.id_str; // id_str = id not rounded more precise console.log('id_str:', retweetId_str); // con.query('SELECT retweetid_str FROM droid_retweets WHERE retweetId_str=?', retweetId_str, function(error,result){ console.log('id_str:', retweetId_str); }); }); // for close 

这是因为for循环在你从con.query得到响应之前已经执行了所有的迭代,这就是为什么它会多次打印最后一个,因为索引处于最后的位置