所以我是 Node 的新手,我确切地知道如何在 PHP 中做我想做的事,尽管我在 Node 中。所以不知道。
我有以下内容。
switch(args[0]) {
case 'games':
var games = con.query("SELECT name FROM games");
message.channel.send('Available Games:');
}
我的连接已经设置好并且可以正常工作。我现在只想知道如何通过数据进行 foreach 以列出我想要的内容。
比如我在游戏中查询了name,所以我想在消息返回时显示所有的游戏名称。
我可以在这里 foreach 吗?完全不确定。
在 php 中我会
foreach($games as $games) {//stuff here}
虽然这不起作用。
谢谢,
凯文
最佳答案
这一切都假设 games 是一个数组,但是您可以做一些事情:
如果您只想将游戏列表写入输出:
var games = con.query("SELECT name FROM games");
message.channel.send('Available Games:' + games.join(', '));
这相当于以下 PHP 代码:
$games = ['halo', 'call of duty', 'destiny 2'];
$message->channel->send('Available Games:' . implode(', ', $games));
如果你想遍历它们:
var games = con.query("SELECT name FROM games");
for (var i = 0; i < games.length; i++) {
var game = games[i];
}
这相当于以下 PHP 代码:
$games = ['halo', 'call of duty', 'destiny 2'];
foreach ($games as $game) {
// $game is in scope here
}
您还可以使用其他数组方法,例如 Array.forEach .但是作用域的处理方式略有不同,可能会有一些问题。如果您不使用臀部循环而不是老式的 for 循环,很多 JavaScript 开发人员会讨厌,but the performance with them is negligibly worse when dealing with small to medium size datasets and relatively the same on larger datasets .
关于javascript - NodeJS如何循环查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56267548/